Codementor Events

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

Published Oct 24, 2018

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

Discover and read more posts from Vignesh M
get started