21 Lazy Loading - biswajitsundara/react GitHub Wiki
Lazy loading in react is a technique that delays the loading of the components until they are actually needed.
- This is used to improve the performance of a web application
- This helps reducing the initial load time of a web page, especially when dealing with large/complex applications.
- Whenever we visit any website, it downloads the JavaScript bundle (chrome dev tools -> source -> static js)
- By default the react code is bundled by webpack and a minified version is shipped to client's browser however it's not enough.
- If it loads everything at once, the bundle size will be really huge and it will impact the performance
- However if we use code splitting & lazy loading, it will break the bundle in chunks and load only what is required.
- Lets say here we have two components Home & About and those include API calls
- Whenever the app loads it will load both the components & it will make those API calls
- This has bad performance (chrome dev tools -> Light house)
- The performance score will be approx 34-35
import About from "./Pages/About";
import Home from "./Pages/Home";
const LazyApp = () => {
return (
<>
<Home />
<About />
</>
);
};
export default LazyApp;
import React, { Suspense } from "react";
const Home = React.lazy(() => import("./Pages/Home"));
const About = React.lazy(() => import("./Pages/About"));
const LazyApp = () => {
return (
<>
<Suspense fallback={<p>Loading..</p>}>
<Home />
</Suspense>
<Suspense fallback={<p>Loading..</p>}>
<About />
</Suspense>
</>
);
};
export default LazyApp;