Lazy Loading in React: Optimizing App Performance
Imagine you have a large website with many pages, but you don’t want everything to load at once when the user visits your website. It would be slow and frustrating. Lazy loading helps by only loading parts of the website as needed, instead of all at once.
Real World Example: Think of a movie streaming platform. When you open the platform, you don’t want to load the details for every movie at once, just the ones you see on the home screen. Only when you click on a movie, the details (images, videos, etc.) for that movie load. This saves time and makes the app faster.
Code Example (Step by Step):
Step 1: Setup React project Make sure you have a React app running (use
npx create-react-app your-app-name
if you don’t have one).Step 2: Import
lazy()
andSuspense
In React, we use thelazy()
function to load components only when they are needed andSuspense
to show a loading state while waiting for the component.Step 3: Code implementation
import React, { Suspense, lazy } from 'react';
// Lazy load the component
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<h1>Lazy Loading Example</h1>
{/* Suspense is used to show a fallback (like a loading message) */}
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
export default App;
Explanation:
lazy(() => import('./LazyComponent'))
: This loads theLazyComponent
only when it’s needed (when it's rendered).Suspense
: We useSuspense
to tell React to show a "Loading..." message while theLazyComponent
is being fetched.
- Step 4: The lazy-loaded component
// LazyComponent.js
import React from 'react';
function LazyComponent() {
return <div>This is a lazily loaded component!</div>;
}
export default LazyComponent;
- Explanation: This component will only be loaded when
LazyComponent
is needed, reducing the initial load time of the app.