• Angular
  • React
  • NextJs
  • Sass

Implement Lazy Loading in React

By Webrecto, October 16, 2023

Introduction

In this article, we will walk through the steps and best practices to implement lazy loading in ReactJs. The lazy function was introduced in the React v16.6.0 to resolve the blank screen when the page loaded. In the application, we import Lazy() function from the react library. The Lazy() function is widely used in React web and mobile development to increase an application's performance by reducing initial loading time.

Implement Lazy Loading in React

What is Lazy Loading?

Lazy loading is a smart effective rule to maintain the web application page loading on the browser. It quickly loads the web page when we use React.lazy() function to load another component in the parent page. The Lazy loading allows to loading of content or high-resolution images in the application on the user demand to reduce the initial load time. The lazy loading function improves the page speed and performance of our web and mobile applications.

The Lazy loading function makes the web application more optimized and easy to handle a large amount of data page. It helps to load web and mobile pages very shortly and shows limited content or images to the user which is needed. This technique provides a boost for efficiency.

When the user scrolls the window from top to bottom, lazy loading loads a small chunk of data to every scroll. In the application web page, the data does not load at one time when the page loads. We send data size requests to REST API to every window scroll for data load. After the service query success, the REST API response sends only demand data.

Syntax

const MyLazyComponent = lazy(load)

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

In the above syntax, the MyLazyComponent component contains a large amount of data, so we use the import function to load the component inside the lazy function. The lazy loading is a React component that allows to loading of components asynchronously.

The lazy load function renders a dynamic import as a regular component.

API Structure for lazy loading

https://dummyjson.com/comments?limit=10&skip=${skip} &select=body,postId

When we call this API in the application to load data, the first time it will load 10 rows of data, when we scroll the page API will again call and send the next 10 rows of data.

Parameters

Lazy loading is a function that returns a Promise, and the React will not call load until the first time you attempt to render the returned component. When the first call is completed, it will wait for it resolve.

Use of lazy loading in React

The Lazy loading is used in huge applications to reduce component load time and speed up performance. First, we recognize the component that loaded more data from the server side and we want to lazy load.

React provides two features from his package one is React.lazy() and the other is React.Suspense. Both are used in components to code splitting and lazy loading.

1: The lazy() function is applied to the dynamic import to the component that you want to lazy load.

import React, { lazy, Suspense } from 'react';
const MyLazyComponent = React.lazy(() => import('./MyLazyComponent'));

2: We use React.Suspense component to wrap lazy-loaded component, The React.Suspense enables the fallback prop for the render react element until the component is completely loaded.

<Suspense fallback={}>
    <MyLazyComponent />
</Suspense>

For example: According to the above image, we get a large amount of images from the REST API to display on the web page. We can use the lazy load function in the component to display the image in chunks when the user pulls down to scroll.

Code-splitting in React

The code-splitting is dynamic changes in any component of the big application. Dynamic imports help to split large bundles of code into small chunks.

The small chunk can be loaded dynamically in the component when the user needs it. If the user gets data from the server side in large amounts, then he can not show the data at one time in the component. that time code-splitting is the best solution to divide data into small chunks. This way we can avoid performance issues in the React application.

The code-splitting technique does not reduce the amount of code in web or mobile applications, It makes fast page loading in react applications.

Using React.Suspense

In case of application load in the browser, React.Suspense provides a better solution to all users and it improves user experience. In the React application, the user does not face any extra space or blank screen while the component is being loaded. The lazy load components are wrapped by React.Suspense component. We can wrap multiple lazy loads or without lazy load components in more than one React.Suspense components in different hierarchy levels.

<Suspense fallback={}>
    ..........
</Suspense>

The Suspense component uses a fallback prop to accept the react component or HTML elements which are rendered as placeholders while all the lazy components are loaded.

Implement Lazy Loading With React Router

React.lazy() function and React.Suspense component is good practice to load more components in the router for navigation. We do not need any extra package for this. We know that a large amount of navigation slows the application when loading the first time because it takes load time.

We can simply use the lazyload function to dynamically import components when it is required for navigation. In a React component, we use code in the return block, we can wrap the Router inside React.Suspense component.

import React, { Suspense } from 'react';
import { Routes, Route } from "react-router-dom"
import Loading from './Loading';

const Dashboard = React.lazy(() => import('./Dashboard'));
const Employee = React.lazy(() => import('./Employee'));
const Customer = React.lazy(() => import('./Customer'));

function App() {
  return (
    <div>
      <Suspense fallback={<Loading />}>
        <Routes>
         <Route path="/" element={ <Dashboard/> } />
         <Route path="employee" element={ <Employee/> } />
         <Route path="customer" element={ <Customer/> } />
        </Routes>
      </Suspense>
    </div>
  )
}

Benefits of Lazy Loading

  • 1: React.Lazy() function reduces initial loading time when using dynamic import.
  • 2: It reduces bundle size and makes lightweight bundle size for load.
  • 3: It helps to split large code into minimum chunks for load-on-demand.
  • 4: Lazy loading improves browser speed for a better user experience.
  • 5: It makes applications very fast with low bandwidth consumption.
  • 6: It is used in big applications and makes applications very smooth.

Harm of Lazy Loading

  • 1: It should not be used in small applications or in which components load less data.
  • 2: The Placeholders can slow down quick scrolling.

Conclusion: Now that we understand the rules of react lazy loading to improve page performance. let's start with how can implement it in a huge React application.

Complete Example

In the below example, we are using the lazy load function for the Employee component. The employee component is using dummy REST API to load large amounts of content to display on the page. So we are maintaining the loading content on the web page through the lazy load technique.

1: First of all, I created a project structure and added two components one is for employee details and the other is for customer details.

2: I have on dummy REST API, so I am consuming API in the employee component for data added to the table.

3: The app component is the parent component in the dummy project. I imported lazy and Suspense from the React package.

4:We will import both the employee and customer components in the App component. Employee component will import from lazy function because a large amount of data exists. The customer component will be added normally.

5:I am using React.Suspense for display of both components. The suspense component is very helpful for reducing white space until both components are loaded.

6: I created another component named Loader to show data is loading in a web page. it will be used in Suspense fallback.

Employee.js

import { useState, useEffect } from "react";
import axios from "axios";

function Employee() {
    const [empdata, setEmpData] = useState();

    useEffect(() => {
        const getData = async () => {
            // Dummy REST API
          axios.get('https://jsonplaceholder.org/users').then((response) => {
            setEmpData(response.data)
          });
        };
        getData();
      }, []);
  return (
    <div className="App">
       <h3>Employee Details:</h3>
       <table width="100%" border="1">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        {
          empdata && empdata.map((emp)=>{
             return(
              <tr>
                <td>{emp.firstname}</td>
                <td>{emp.lastname}</td>
              </tr>
             )
            })
        }
       </table>
    </div>
  );
}
export default Employee;

App.js

import { Suspense, lazy } from "react";
import './App.css';
import Loader from "./Loader/Loader";
import Customer from "./Customer/Customer";
const Employee = lazy(() => import('./Employee/Employee')); // Dynamic import
function App() {
  return (
    <div className="App">
      <h2>React Lazy Loading Example::webrecto.com</h2>
      <Suspense fallback={<Loader />}>
        <Employee/>
        <Customer/>
      </Suspense>
    </div>
  );
}
export default App;

Find the print screen of the output.

Implement Lazy Loading in React

Reference

Download Source Code