DEV Community

loading...

React.lazy, What and how to use in your app

Vignesh M
I build excellent modern web applications. CTO at NovelShip. JavaScript <3 Python
・1 min read

React 16.6 is out and with it comes the new Lazy API. The Rreact.lazy function lets you render a dynamic import as a regular component.

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

Usage:

const LazyComponent = React.lazy(() => import('./Component'));

Show a fallback with Suspense

Wrap the component where it's used with Suspense and pass a fallback. The fallback prop accepts any React elements that you want to render while waiting for the component to load.

<Suspense fallback={<div>Loading Component...</div>}>
  <LazyComponent />
</Suspense>

I made a simple example to show

The app shows a Press Me!! button which when pressed fetches a random user data from randomuser then loads and renders the User component.

const User = React.lazy(() => import('./User'));

....

<React.Suspense fallback={<div>Loading Component...</div>}>
  {user && <User user={user}/>}
  {loading ? (
    <div>Loading User...</div>
  ) : (
    !user && <button onClick={this.loadUser}>Press Me!!</button>
  )}
</React.Suspense>

Live: react-lazy-example
Code: github

Run the app, open your Network tab in Dev console, Press the button and see the lazily loaded javascript chunk. 🎉🎉

Discussion (5)

Collapse
conantonakos profile image
Constantine Antonakos • Edited

Would this be a good use case for lazy loading a component that imports a large npm package? In other words, I used to dynamically import these type of packages with import() in the React component lifecycle before rendering something.

Collapse
vigzmv profile image
Vignesh M Author

Yes, just be sure that package isn't already imported by any other component.

Collapse
hafidzamr profile image
hafidzamr

using React.lazy every import component is effective? I'm so confused about what condition should use Reac.lazy

Collapse
dceddia profile image
Dave Ceddia

Nice demo! Thanks for putting up a working example :) FYI the Github link is broken though.

Collapse
vigzmv profile image
Vignesh M Author

Thanks for informing! I forgot to make it public 😭

Forem Open with the Forem app