How to implement lazy loading in React.js?

Member

by orpha , in category: Javascript , 8 months ago

How to implement lazy loading in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 8 months ago

@orpha 

To implement lazy loading in React.js, you can make use of React's lazy function along with the Suspense component.


Here are the steps to follow:

  1. Import the lazy function from the react package at the top of your component file:
1
import React, { lazy, Suspense } from 'react';


  1. Create a separate file for the component that you want to lazy load. For example, create a file named LazyComponent.js:
1
2
3
4
5
6
7
import React from 'react';

const LazyComponent = () => {
  return <div>This is the lazy loaded component!</div>;
};

export default LazyComponent;


  1. In your main component file, import the lazy component using the lazy function:
1
2
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));


  1. Wrap the lazy component with the Suspense component and provide a fallback UI while the component is loading:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const App = () => {
  return (
    <div>
      <h1>Lazy Loading Example</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
};


  1. That's it! Now, when LazyComponent is about to be rendered, it will be lazy-loaded automatically and the fallback UI will show until it finishes loading.


Lazy loading allows you to improve initial page load time by splitting your code into smaller chunks, and only loading them when needed.