Lazy loading in react
Tags: react, javascript
Published: 2022-07-13 07:06:31

Hello guys,

In this article we will see what is lazy loading and how can we lazy load a component.

**Lazy loading** means loading a component when it is required.

Let's consider a scenario where we have a list of persons and when we click on any of them, a dialog opens which shows the details about the person. Now this dialog opens only when we click the persons. Let's compare this scenario with the definition of lazy loading. Dialog component is not required when we are displaying the list of persons. It is required only when we click on any of the persons. So we can lazy load the Dialog component.

Let's name this Dialog as `PersonDetails` component and let's lazy load it.

To do lazy load, we can either use **lazy** provided by react or we can use some other npm libraries. I am going to use @loadable/component.

Let's install @lodable/component first.

```javascript
npm i @loadable/component;
```

Below is our App.js component. I have used create-react-app to create the project.

```javascript
import './App.css';
import { useState } from 'react';
import loadable from '@loadable/component';
// **Without lazy loading**
// import PersonDetails from './components/PersonDetails';

// **With lazy loading**
const PersonDetails = loadable(() => import('./components/PersonDetails'),
{ fallback: <div>Loading...</div> });

const persons = [
  {
    name: 'John',
    lastName: 'Doe',
    dob: '15th June 1990',
    place: 'London',
    contry: 'The Great Britain',
    contact: '123456'
  },
  {
    name: 'Jane',
    lastName: 'Doe',
    dob: '15th July 1990',
    place: 'London',
    contry: 'The Great Britain',
    contact: '654321'
  },
  {
    name: 'Frank',
    lastName: 'Doe',
    dob: '15th August 1992',
    place: 'New York',
    contry: 'USA',
    contact: '123456'
  }
];

function App() {
  const [person, setPerson] = useState(null);
  const handleClick = (person) => () => {
    setPerson(person);
  }

  const handleClose = () => {
    setPerson(null);
  }

  return (
    <div className="App">
      {persons.map(person => {
        return (
          <div key={person.name} className='person' onClick={handleClick(person)}>
            <span>{person.name}</span>
            {' '}
            <span>{person.lastName}</span>
          </div>
        )
      })}
      {person && <PersonDetails person={person} onClose={handleClose} />}
    </div>
  );
}

export default App;

```
As you can see how I am using @loadable/component to lazy load `PersonDetails` component.

```javascript
const PersonDetails = loadable(() => import('./components/PersonDetails'),
{ fallback: <div>Loading...</div> });
```
 
Now why lazy load and how does it affect our application.

Without lazy load we would include the `PersonDetails` component in the bundle.js thereby increasing the bundle size where with lazy load we extract the `PersonDetails` to another chunk which gets loaded only when we click on the person list.

Below image shows how everything was bundled into one js(**bundle.js**) (without lazy loading).
![Without lazy loading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2bv94dshtcoifvoy46o.PNG)

Below image shows how we extracted `PersonDetails` into a separate js chunk (with lazy loading) and it gets loaded only after we click on the person list.
![With lazy loading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tenpgzrqef638svtpba4.PNG)

Here is the github [lazy loading](https://github.com/abhmohan/lazyloading)

That's all for this article.
Thank you for reading.