DEV Community

Vignesh M
Vignesh M

Posted on

10 2

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.

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (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

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

Thanks for informing! I forgot to make it public 😭

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️