DEV Community

Vignesh M
Vignesh M

Posted on

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

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.


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 />

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>

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. 🎉🎉

Top comments (5)

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.

vigzmv profile image
Vignesh M

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

hafidzamr profile image

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

dceddia profile image
Dave Ceddia

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

vigzmv profile image
Vignesh M

Thanks for informing! I forgot to make it public 😭