Lazy Loading in React
Tags: webdev, react, reactjsdevelopment, webperf
Published: 2023-08-28 10:46:03

If you know about web performance, then you might be familiar with the concept of Lazy Loading.As the name suggest, this technique is used to load website data lazily or with some sort of delay. 
According to mdn web docs - "Lazy loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It's a way to shorten the length of the critical rendering path, which translates into reduced page load times."

I know , the definition is bit hard to understand. In simple terms it says that only those resources are loaded to browser that are needed to render the page, all other resources are blocked away. It gives two major advantages, first , it reduces the loading time and storage of the web browser and second, it also reduces the bandwidth of your internet.

Now that  you are conscious with the primary understanding of the Lazy Loading, we will explore how this concept is utilised in React. As you are familiar, React uses component approach to render the webpage. For smaller websites, loading all the components at once may not affect the performance, but for large websites, loading all the resources at once can be a  nightmare. So in react we use `lazy` and `Suspense` to apply  this strategy.

Lets learn how to apply in our app. But wait, first I'll show you what does it mean to load resources at once. 

I have created 3 routes for my app using `react-router-dom`

### App.jsx

```jsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Angular from "./pages/Angular";
import Vue from "./pages/Vue";
import "./App.css";

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/angular" element={<Angular />} />
          <Route path="/vue" element={<Vue />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;
```
I have create three routes for my app. Each webpage has heading and a image. 

1. - Run the React server and open your browser.
2. - On your server port , open `chrome-dev-tools` by inspecting the page or press `ctrl+shift+i`. 
3. - Navigate to `sources` tab .
4. - In your `localhost` folder you can verify that, although we  have no use of other routes data to display `Home` component. But still it is loading all the resources. 


![chrome-dev-tools before lazy loading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b2bnsh0sy8mdtc80rbj.png)

Now you can see that all extra resources are using web storage and bandwidth that can be reduced.

Lets try to implement Lazy Loading Strategy in our app.We will create a 'loading' screen for our app.

### Loader.jsx

```jsx
import React from "react";

const Loader = () => {
  return (
    <>
      <div>
        <h1>...</h1>
      </div>
    </>
  );
};

export default Loader;
```

For developers sake , React provide inbuilt tool `lazy` and `Suspense`
We have to make some changes in the `App.jsx` where we define our routes. 

### App.jsx

```jsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { lazy, Suspense } from "react";
import Loader from "./Loader";
import "./App.css";

const Home = lazy(() => import("./pages/Home"));
const Angular = lazy(() => import("./pages/Angular"));
const Vue = lazy(() => import("./pages/Vue"));

function App() {
  return (
    <>
      <BrowserRouter>
        <Suspense fallback={<Loader />}>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/angular" element={<Angular />} />
            <Route path="/vue" element={<Vue />} />
          </Routes>
        </Suspense>
      </BrowserRouter>
    </>
  );
}

export default App;
```
And that's it. We have added lazy loading in our react app.
Voila!.

To verify that our lazy loading is working properly, lets again check our `sources` tab in `chrome dev tools`.

![chrome-dev-tools after lazy loading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4tdl3ux5ttovfoh5ke7.png)

As it is visible, our app load only those resources that are needed to render Home page.

This is just a small app, so this doesn't seem to effect much performance, but as your app grows managing resources become crucial. 
We can apply lazy-loading concept to any component , not just on routes.Also, for `Loader` we can use any spinner, progress, text, image as per our requirement. 

For this tutorial I have used Vite for building my react app , but it works similar to `create-react-app`.

I hope you got get the better understanding of lazy loading and how we can use it in out react app.

Feel free to comment if you have any doubt.

References - 
[mdn](https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading)
[react docs](https://react.dev/reference/react/lazy)

Thank you for reading.
Connect me on [sidme.tech](https://sidme.tech/)