React Lazy, Suspense, and Code Splitting

Amir Mustafa
3 min readFeb 20, 2021

--

→ Before deployment, React JS is bundled into a single file and deployed.

→ Bundling is great, but as your app grows, your bundle will grow too. Especially if you are including large third-party libraries. You need to keep an eye on the code you are including in your bundle so that you don’t accidentally make it so large that your app takes a long time to load.

→ When we are having an application, its bundle file keeps on growing. Instead of making a 25 MB file we can split it and divide the bundle size.

→ To avoid winding up with a large bundle, it’s good to get ahead of the problem and start “splitting” your bundle. Code-Splitting is a feature supported by bundlers like Webpack, Rollup and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime.

→ Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code in your app, you’ve avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.

→ The way we can import synchronous modules.

import Foo from './Foo';    // this is for synchronous, declarative,
// webpack finds it and ready it line by line

→ The way we can load asynchronous modules. It comes with the concept of dynamic loading.

import('./Foo').then(Foo =>
console.log(Foo)
)

→ In the application you must have used some concepts, whenever some data is fetched from API, meanwhile we have used loaders and goes away when data is fetched successfully. Easier way is using React-loadable

Example:

Cast.js (Component 1)

Description.js (Component 2)

App.js (Regular Way) — Main Component

App.js

O/P:

App.js (With Lazy Load) — Main Component

→ Lazy load is the optimization trick.

→ Convert regular import into asynchronous import

var Cast = React.lazy(() => import('./Cast'));// import Cast from './Cast';   // Regular

→ So the component which will import late should be added in <Suspense>. Inside Suspense Component we keep all the asynchronous components that are dynamic import.

eg. purposely for the demo we delayed two components — 500 milliseconds and 1000 milliseconds. So it will load all in 1000 milliseconds

→ The React.lazy function lets you render a dynamic import as a regular component.

App.js (With lazyload)

Conclusion:

  1. Use asynchronous imports on those components which will take time to load. eg. images, videos, or some time-consuming response.
  2. The page will load, in the meantime, other components will lazily load.

Check code here

Reference doc

--

--

Amir Mustafa
Amir Mustafa

Written by Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/

No responses yet