Introduction
When a React application is running, its partial load time increases due to the large JavaScript bundle size. The result is that users have to download more code before they can interact with your application, resulting in slower load times and a poor user experience.
One of the easiest ways to improve performance is Lazy Loading, which allows components to be loaded only when they are actually needed.
In this post, we'll learn how to implement lazy loading in React using React.lazy() and Suspense
What is Lazy Loading?
Lazy loading is a technique where components are loaded on demand instead of being included in the initial JavaScript bundle.
Without lazy loading, all components are downloaded when the application starts.
With lazy loading, only the code required for the current page is downloaded initially.
Why Use Lazy Loading?
Benefits
- Smaller initial bundle size
- Faster page load times
- Better user experience
- Reduced bandwidth usage
- Improved Core Web Vitals
React provides the lazy() function to dynamically import components. Instead of loading the component immediately, React downloads it only when it needs to render it.
import { lazy } from "react";
const ProductDetail = lazy(() => import("./pages/ProductDetail"));
Since a lazy-loaded component takes time to download, React needs a fallback UI while loading.
import { Suspense, lazy } from "react";
const ProductDetail = lazy(() => import("./pages/ProductDetail"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<ProductDetail />
</Suspense>
);
}
Before using Lazy loading, we have to ensure important points:
- Components must have a default export
export default ProductDetail;
- Declare lazy imports outside the Component
const Orders = lazy(() => import("./pages/Orders"));
function App(){
return <>
...
<>
}
Thank you for reading the post. If you have any query, feel free to comment below. I will reply to each comment.
Top comments (0)