Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Code Splitting with React.lazy and Suspense
Ayo Ashiru
Ayo Ashiru

Posted on • Edited on

     

Code Splitting with React.lazy and Suspense

In modern web development, performance is paramount. Users expect fast-loading applications, and one of the most effective strategies to achieve this is through code splitting. Code splitting allows you to break your application into smaller chunks, loading only the necessary code when needed. This article explores how to implement code splitting in React usingReact.lazy andSuspense.

Understanding Code Splitting

Code splitting is the process of dividing your application into smaller bundles that can be loaded on demand. This is particularly important for large applications, where shipping a single, massive JavaScript bundle can lead to slow load times and a poor user experience. By splitting your code, you can ensure that users only download the code they need, when they need it.

The Role of Bundling

Most React applications use bundlers like Webpack, Rollup, or Browserify to combine files into a single bundle. While bundling is efficient, it can lead to large file sizes as your application grows. Code splitting helps mitigate this issue by allowing you to load only the necessary parts of your application.

Dynamic Imports

The dynamic import() syntax is the foundation of code splitting in JavaScript. It allows you to load modules asynchronously, which is crucial for implementing code splitting in React.

// Before code splittingimport{add}from'./math';console.log(add(16,26));// After code splittingimport("./math").then(math=>{console.log(math.add(16,26));});
Enter fullscreen modeExit fullscreen mode

When usingimport(), the bundler automatically creates separate chunks for the imported modules.

Using React.lazy

React provides a built-in way to implement code splitting at the component level throughReact.lazy. This function allows you to define a component that will be loaded dynamically.

Example:

importReact,{lazy}from'react';constAvatarComponent=lazy(()=>import('./AvatarComponent'));constDetailsComponent=()=>(<div><AvatarComponent/></div>);
Enter fullscreen modeExit fullscreen mode

In this example,AvatarComponent will only be loaded whenDetailsComponent is rendered, reducing the initial load time.

Introducing Suspense

WhileReact.lazy handles the loading of components, it does not manage the loading state. This is whereSuspense comes in.Suspense allows you to define a fallback UI that will be displayed while the lazy-loaded component is being fetched.

Example:

importReact,{lazy,Suspense}from'react';constAvatarComponent=lazy(()=>import('./AvatarComponent'));constrenderLoader=()=><p>Loading...</p>;constDetailsComponent=()=>(<Suspensefallback={renderLoader()}><AvatarComponent/></Suspense>);
Enter fullscreen modeExit fullscreen mode

In this example, whileAvatarComponent is loading, the user will see a "Loading..." message. This enhances the user experience by providing feedback during the loading process.

Handling Multiple Components

Suspense can also manage multiple lazy-loaded components simultaneously. This is useful for reducing the number of loading indicators displayed to the user.

Example:

importReact,{lazy,Suspense}from'react';constAvatarComponent=lazy(()=>import('./AvatarComponent'));constInfoComponent=lazy(()=>import('./InfoComponent'));constrenderLoader=()=><p>Loading...</p>;constDetailsComponent=()=>(<Suspensefallback={renderLoader()}><AvatarComponent/><InfoComponent/></Suspense>);
Enter fullscreen modeExit fullscreen mode

In this case, both components will be loaded together, and the user will see a single loading indicator until both are ready.

Error Boundaries

When dealing with lazy-loaded components, it's essential to handle potential loading failures. React provides a pattern for this through error boundaries. An error boundary can catch errors during rendering and display a fallback UI.

Example:

importReact,{lazy,Suspense}from'react';constAvatarComponent=lazy(()=>import('./AvatarComponent'));classErrorBoundaryextendsReact.Component{constructor(props){super(props);this.state={hasError:false};}staticgetDerivedStateFromError(error){return{hasError:true};}render(){if(this.state.hasError){return<p>Loadingfailed!Pleasereload.</p>;}returnthis.props.children;}}constDetailsComponent=()=>(<ErrorBoundary><Suspensefallback={<p>Loading...</p>}><AvatarComponent/></Suspense></ErrorBoundary>);
Enter fullscreen modeExit fullscreen mode

In this example, if AvatarComponent fails to load, the user will see a friendly error message instead of a broken UI.

Route-Based Code Splitting

One of the most effective places to implement code splitting is at the route level. This is particularly useful in single-page applications (SPAs) where different routes can load different components.

Example:

importReact,{Suspense,lazy}from'react';import{BrowserRouterasRouter,Routes,Route}from'react-router-dom';constHome=lazy(()=>import('./routes/Home'));constAbout=lazy(()=>import('./routes/About'));constApp=()=>(<Router><Suspensefallback={<div>Loading...</div>}><Routes><Routepath="/"element={<Home/>}/><Routepath="/about"element={<About/>}/></Routes></Suspense></Router>);
Enter fullscreen modeExit fullscreen mode

In this example, theHome andAbout components are loaded only when their respective routes are accessed, optimizing the initial load time.

Conclusion

Code splitting is a powerful technique that can significantly enhance the performance of your React applications. By usingReact.lazy andSuspense, you can easily implement code splitting at the component level, ensuring that users only download the code they need. This not only improves load times but also enhances the overall user experience.

As you develop your React applications, consider where you can apply code splitting to optimize performance. Start with route-based splitting and identify large components that can be loaded on demand. With these strategies, you can create fast, efficient applications that delight your users.

Follow me for more insights on React, TypeScript, and modern web development practices!👨‍💻

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
tjasper profile image
Oluwaloseyi Oluwatofunmi Emmanuel
Cloud Engineer | DevOps Enthusiast | FinOps | Streamlining Cloud Infrastructure for Seamless Operations
  • Email
  • Location
    Lagos, Nigeria.
  • Education
    UNILAG, SKILL SCHULE
  • Pronouns
    He/Him
  • Work
    Cloud Engineer
  • Joined

An intriguing and captivating source

CollapseExpand
 
ayoashy profile image
Ayo Ashiru
always learning, forever building...
  • Email
  • Education
    University of Lagos
  • Pronouns
    he/him
  • Work
    Software Engineer at Flyboku
  • Joined

Thanks🙏🏾

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

always learning, forever building...
  • Education
    University of Lagos
  • Pronouns
    he/him
  • Work
    Software Engineer at Flyboku
  • Joined

More fromAyo Ashiru

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp