Introduction

Lazy loading is a performance optimization technique for both web and mobile applications. In this article, we are going to explore what lazy loading is and how to implement lazy loading in React applications.

Lazy Loading

Advantages

How to implement Lazy Loading in React Applications

React has built-in support for lazy loading components. There are two features to implement lazy loading in React applications.

  1. React.lazy()
  2. React.Suspense

React.lazy()

React.lazy() eliminates the use of a third-party library such as react-loadable for lazy loading.

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

//Consume
<div>
    <User/>
</div>

React.Suspense

Multiple lazy components can be wrapped with the one suspense component.

<div>
    <Suspense fallback={<div>loading...</div>}
        <User/>
    </Suspense>
</div>

Example

I have created a simple application for lazy loading. In this application, there are two components "Product" and "Brand" which are loaded inside the "Layout" component.

<div>
    <div>
      <Product />
    </div>
    <div>
      <React.Suspense fallback={<div>Loading...</div>}>
        <BrandComponent />
      </React.Suspense>
    </div>
</div>

The "Product" component will load initially.

<div>
  <Product />
</div>

The "Brand" component will load after 5 seconds using React.lazy().

const BrandComponent = React.lazy(
  () =>
    new Promise((resolve, reject) =>
      setTimeout(() => resolve(import("./Brand")), 5000)
    )
);
<div>
  <React.Suspense fallback={<div>Loading...</div>}>
    <BrandComponent />
  </React.Suspense>
</div>

Added below fallback UI to display while "Brand" component being loaded using React.Suspense.

<React.Suspense fallback={<div>Loading...</div>}>

Initial load of the application,

After 5 seconds,

Summary

I hope you have liked it and learned about lazy loading and implement lazy loading in React applications.