avatar

Hassan khan

Last updated: November 07,2022

Lazy loading in reactJS

Lazy loading in react


Lazy loading in react in simple words is loading a specific part of the site or code when required. When we create a build of the reactjs application, then all js files are combined in one file. It looks a little confusing but doesn't worry will explain with an example.


React lazy loading example

For example, we have created a school management system where there are three user roles (administration, teacher, and student). When a student login into the application the whole website will be downloaded to the browser while the student only needs the student portion of the website. So to solve this problem, react lazy loading helps us to prevent wastage of resources and improve the performance of a website.

1
2
3
4
5
6
7
8
9
10
11
  import React, { Suspense } from 'react';
  const OtherComponent = React.lazy(() => import('./OtherComponent'));
  function MyComponent() {
    return (
      <div>
        <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
        </Suspense>
      </div>
    );
  }

Share