Lazy Loading Components
Learn how to load React components only when they are needed, reduce the initial JavaScript loading cost, and improve the performance of React applications using React.lazy and Suspense.
1. Introduction to Lazy Loading
Lazy loading is a technique in which a component or resource is loaded only when it is required. Instead of loading every component immediately when an application starts, we can load selected components when the user needs them.
Consider a student management application that contains a dashboard, reports page, student details page, and settings page. A student who opens the dashboard may not immediately need the reports or settings components.
Lazy loading helps separate these components into smaller loading units so that some code can be downloaded when required.
2. Why Do We Need Lazy Loading?
Faster Initial Loading
The browser may need to download and process less application code before displaying the initial screen.
Smaller Initial Bundle
Separating code into chunks can reduce the size of the JavaScript required at startup.
On-Demand Loading
Less frequently used components can load when the user navigates to the relevant feature.
Better Scalability
Large applications can organize features into separate loading units.
3. Understanding React.lazy
React provides the lazy function to defer loading a component's code until React first attempts to render that component. The component must be loaded through a dynamic import that resolves to a default export.
import { lazy, Suspense } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<MyComponent />
</Suspense>
);
}
export default App;
Explanation:
lazy()declares a component that React loads on demand.import()dynamically loads the component module.Suspensedisplays fallback content while the lazy component is loading.fallbackcan contain a loading message, spinner, or skeleton UI.
4. Creating a Component Without Lazy Loading
First, consider a normal component import. The imported component becomes part of the application's normal module dependency graph. Depending on the build configuration, it may be included in the initial bundle.
export default function Reports() {
return (
<div>
<h2>Reports Page</h2>
<p>View student performance reports.</p>
</div>
);
}
import Reports from './Reports';
export default function App() {
return (
<div>
<h1>CIIT Training Institute</h1>
<Reports />
</div>
);
}
In this example, Reports is imported normally. If the component is part of the initial bundle, its code must be downloaded before that bundle can be used. The exact bundling behavior depends on the build tool and configuration.
5. Implementing Lazy Loading
We can update the previous example to load the Reports component on demand by using React.lazy and Suspense.
import { lazy, Suspense, useState } from 'react';
const Reports = lazy(() => import('./Reports'));
export default function App() {
const [showReports, setShowReports] = useState(false);
return (
<div>
<h1>CIIT Training Institute</h1>
<button onClick={() => setShowReports(true)}>
Open Reports
</button>
{showReports && (
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
)}
</div>
);
}
How it works:
- The application initially displays the heading and button.
- The Reports component is not rendered initially.
- When the user clicks Open Reports, the state changes.
- React attempts to render Reports and loads its module if needed.
- Suspense displays the fallback while the component is loading.
- When the module is ready, React displays the Reports component.
6. Understanding Suspense
Suspense lets you specify fallback content while a supported child is waiting for something, such as a lazy-loaded component module. It provides a convenient way to display loading feedback instead of leaving an empty area.
import { lazy, Suspense } from 'react';
const StudentDetails = lazy(
() => import('./StudentDetails')
);
export default function SuspenseExample() {
return (
<div>
<h2>Student Management</h2>
<Suspense
fallback={<p>Loading student details...</p>}
>
<StudentDetails />
</Suspense>
</div>
);
}
While StudentDetails is loading, the fallback message can be displayed. After the module is ready, React displays the component.
7. Lazy Loading with React Router
In larger applications, different routes often represent separate features. Lazy loading route components can allow each feature's code to be loaded when a user navigates to that route.
import { lazy, Suspense } from 'react';
import {
BrowserRouter,
Routes,
Route,
Link
} from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Reports = lazy(() => import('./pages/Reports'));
export default function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
{' | '}
<Link to="/reports">Reports</Link>
</nav>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/reports"
element={<Reports />}
/>
</Routes>
</Suspense>
</BrowserRouter>
);
}
In this example, Home and Reports are lazy-loaded route components. A user who visits the Home route does not necessarily need to download the Reports component code immediately.
./pages/Home and ./pages/Reports
each have a default export.
8. Lazy Loading vs Normal Imports
| Feature | Normal Import | Lazy Loading |
|---|---|---|
| Import style | Static import | Dynamic import through React.lazy |
| Loading behavior | Depends on how the build bundles the module | Module loading is deferred until the component is first rendered |
| Loading fallback | Not provided by the import itself | Suspense can display fallback content |
| Common use | Components needed immediately | Large or less frequently used components |
| Initial bundle | May include the imported module | Can move the module into a separate chunk |
9. Common Mistakes
- Forgetting Suspense: A lazy component needs an appropriate Suspense boundary above it.
- Missing default export: React.lazy expects the imported module to resolve to an object whose default export is the component.
- Lazy loading everything: Components needed immediately may not benefit from deferred loading.
- Ignoring loading feedback: A suitable fallback helps users understand that content is loading.
- Ignoring import failures: Use an Error Boundary or another suitable error-handling strategy for failed component loading.
- Creating lazy components repeatedly: Declare lazy components outside the rendering component so their identity remains stable.
10. Best Practices
- Lazy-load large features that are not required for the initial screen.
- Use Suspense with a meaningful loading message or skeleton.
- Consider route-level code splitting for large applications.
- Keep lazy component declarations outside the parent component's render function.
- Handle loading failures with an appropriate error-handling strategy.
- Measure the initial bundle size and loading experience before and after code splitting.
11. Practice Tasks
- Create a Reports component and import it normally into App.jsx.
- Convert the Reports component to use React.lazy.
- Wrap the lazy component with Suspense and display a loading message.
- Use a button to load the Reports component only when requested.
- Create Home and Reports routes and lazy-load both pages.
- Compare the application's initial loading behavior before and after code splitting.
Summary
Lazy loading allows React applications to defer loading selected components until they are required. React.lazy works with dynamic imports, while Suspense provides fallback content during loading. Lazy loading can reduce the JavaScript needed for the initial screen, especially when used for large features or route components. Selecting appropriate components, providing loading feedback, handling failures, and measuring the result are important parts of an effective implementation.