React lazy loading
Created By: chatGPT
In React, lazy loading is a powerful feature that enables you to load components only when they are needed, which can significantly improve the performance of your application. This is particularly useful for large components or libraries that are not immediately necessary on initial render. It can be easily implemented using the
React.lazy
function along with Suspense
.const LazyComponent = React.lazy(() => import('./LazyComponent'));
const App = () => {
return (
<div>
<h1>My App</h1>
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
</div>
);
};
The
React.lazy
function takes a function that returns a dynamic import and returns a React component that dynamically loads the module. The Suspense
component is used to wrap the lazy-loaded component and provides a fallback UI that can be displayed while the component is being loaded.const LazyScrollComponent = React.lazy(() => import('./ScrollComponent'));
const AppWithScroll = () => {
return (
<React.Suspense fallback={<div>Loading Scroll Component...</div>}>
<LazyScrollComponent />
</React.Suspense>
);
};
Key Benefits of using lazy loading include reduced load times and increased performance as the initial bundle size is smaller. Components are only loaded as required, keeping the application responsive without overwhelming it with unnecessary resources.
const LazyImageComponent = React.lazy(() => import('./ImageComponent'));
const AppWithImage = () => {
return (
<div>
<h2>Image Gallery</h2>
<React.Suspense fallback={<div>Loading Images...</div>}>
<LazyImageComponent />
</React.Suspense>
</div>
);
};
When implementing lazy loading, keep in mind that each lazy-loaded component will have its own loading state and may impact the user experience if not handled appropriately. Consider showing loading indicators or skeleton screens to enhance perceived performance.
const AppWithLoader = () => {
const [loading, setLoading] = useState(true);
const handleLoad = () => {
setLoading(false);
};
return (
<div>
{loading && <div>Loading App...</div>}
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent onLoad={handleLoad} />
</React.Suspense>
</div>
);
};