08 Feb 2024
Lazy loading in ReactJS is a technique where components or resources are loaded only when they are needed, rather than loading everything upfront. It helps improve performance by reducing the initial load time of the application and loading only the necessary parts when they are required.
Lazy loading approach can significantly improve the performance of React applications by reducing the initial bundle size and only loading the necessary components when they are required.
Lazy loading is typically implemented using React's React.lazy() function along with the Suspense component. Here's how it works:
- React.lazy(): This function allows you to dynamically import a component. It takes a function that must call a dynamic import() function which resolves to a module with a React component. For example:
const MyComponent = React.lazy(() => import('./MyComponent'));
- Suspense Component: The
Suspensecomponent is used to specify the fallback content while the lazy-loaded component is being loaded. It accepts afallbackprop which can be any React element to display while the component is loading.
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
When the <MyComponent /> is rendered, React will automatically start loading the component using the dynamic import(). While the component is being loaded, the fallback content specified in the Suspense component will be displayed. Once the component is loaded, it will be rendered in place of the fallback content.
Lazy loading is particularly useful for large applications with many components where loading everything upfront might degrade performance. It allows developers to split the application into smaller chunks and load them on demand, resulting in faster initial load times and better user experience.