ReactJS - lazy()



Lazy loading is a React method that allows us to delay loading a component's code until it is required. Lazy loading allows us to load specific pieces of our code just when they are ready to use, rather than loading everything when our program starts.

Syntax

import { lazy } from 'react';

const MyComponent = lazy(load)

Parameters

load − It is a function which returns a Promise. React will only call this function the first time we try to render the component.

Return Value

The lazy function returns a React component for use in our program. Attempting to render the code while it is still loading will lead it to suspend, and we can use <Suspense> to display a loading message.

Examples

Example 1

Now we are going to create a complete application with lazy loading that needs multiple files and configurations. It is a simple example of a React project that makes use of lazy loading for components. So we will create 2 components called ComponentA and ComponentB. And then we will call these components in the main component called App.

ComponentA.js

import React from 'react';

const ComponentA = () => {
   return <div>This is Component A</div>;
};

export default ComponentA;

ComponentB.js

import React from 'react';

const ComponentB = () => {
return <div>This is Component B</div>;
};

export default ComponentB;

App.js

import React, { lazy, Suspense } from 'react';

const ComponentA = lazy(() => import('./ComponentA'));
const ComponentB = lazy(() => import('./ComponentB'));

const App = () => {
   return (
      <div>
         <h1>Lazy Loading App</h1>
         <Suspense fallback={<div>Loading...</div>}>
            <ComponentA />
            <ComponentB />
         </Suspense>
      </div>
   );
};

export default App;

Output

lazy loading app

In the browser, navigate to http://localhost:3000 and we should see our lazy-loaded components.

This is a simple example, lazy loading is frequently used for larger components or routes for better performance. Also, for more complex lazy loading in a multi-page application, consider leveraging technologies like React Router.

Example 2

Let us create a basic React app that renders a dynamic list of things with a lazy loading method. We will have a main component (ItemList) and individual item components that will be loaded concurrently.

// src/ItemList.js
import React, { lazy, Suspense } from 'react';
import Loading from './Loading';

// Lazy load Item component
const Item = lazy(() => delayForDemo(import('./Item')));

const itemsData = [
   { id: 1, name: 'Item 1' },
   { id: 2, name: 'Item 2' },
   { id: 3, name: 'Item 3' },
];

const ItemList = () => {
   return (
      <div>
         <h2>Item List</h2>
         <Suspense fallback={<Loading />}>
         {itemsData.map((item) => (
            <Item key={item.id} name={item.name} />
         ))}
         </Suspense>
      </div>
   );
};

export default ItemList;

// Add a fixed delay 
function delayForDemo(promise) {
   return new Promise(resolve => {
      setTimeout(resolve, 2000);
   }).then(() => promise);
}

Loading.js

export default function Loading() {
   return <p><i>Loading...</i></p>;
}

src/App.js

import React from 'react';
import ItemList from './ItemList';

function App() {
   return (
      <div>
         <h1>Lazy Loading Example</h1>
         <ItemList />
      </div>
   );
}

export default App;

Output

lazy loading example lazy loading item list

In the browser, navigate to http://localhost:3000 and we should see our lazy-loaded list of items.

This example shows how to use lazy loading to improve our app's initial loading performance, especially when working with huge lists of components.

Example 3

Let us create another example where we will use the lazy method to load a component which contains an image.

LazyComponent.js

import React from 'react';

const LazyComponent = () => {
   return (
      <div>
         <p>This component contains a image:</p>
         <img
         src="https://via.placeholder.com/300"
         alt="Lazy Loaded Image"
         />
      </div>
   );
};

export default LazyComponent;

Loading.js

export default function Loading() {
   return <p><i>Loading...</i></p>;
}

App.js

import React, { lazy, Suspense } from 'react';
import './App.css'

// Lazy load the component
const LazyComponent = lazy(() => delayForDemo(import('./LazyComponent')));

const App = () => {
   return (
      <div className='App'>
         <h1>Lazy Loading Example</h1>
         <p>This is the main component.</p>
         
         {/* Suspense to handle the lazy loading */}
         <Suspense fallback={<div>Loading...</div>}>
            <LazyComponent />
         </Suspense>
      </div>
   );
};

export default App;

// Add a fixed delay
function delayForDemo(promise) {
   return new Promise(resolve => {
      setTimeout(resolve, 2000);
   }).then(() => promise);
}

Output

main component

In this example, the LazyComponent component contains an image loaded from a source. We use the lazy method to load this component in the App component.

As before, the Suspense component handles the asynchronous loading of the lazy component and displays a fallback UI (in this case, a simple "Loading..." message) while the component is being loaded.

Summary

Lazy loading in React improves performance by loading only the code that is required, making our app faster and more efficient. We have created two simple applications using a lazy loading method. These are very simple examples, lazy loading is frequently used for larger components or routes to increase performance.

reactjs_reference_api.htm
Advertisements