Lazy Loading Components in React – Complete Detailed Notes
Lazy Loading Components is a React technique that delays loading a component's JavaScript code until the component is needed. It helps reduce the initial JavaScript bundle size, improve loading performance, and make React applications more efficient.
React provides the lazy() function and the Suspense component to support lazy loading and display a fallback interface while a component's code is loading.
1. What Is Lazy Loading in React?
Lazy loading means loading resources only when they are required instead of loading everything immediately when an application starts.
In a React application, components that are not needed during the initial page render can be loaded dynamically when users navigate to a page or open a particular section.
Example Scenario
Imagine an application containing a Home page, Dashboard, Reports page, and Settings page. If a user initially visits only the Home page, the application may not need to download the code for Reports and Settings immediately.
Lazy loading allows those components to load when they are required.
Basic Concept
React Application
|
v
Initial Page Loads
|
v
User Opens Reports
|
v
Reports Component Loads
|
v
Reports UI Displays
2. Why Do We Use Lazy Loading?
- Reduce initial bundle size: Components that are not immediately required can be excluded from the initial JavaScript download.
- Improve initial loading: Smaller initial bundles can help the application become usable sooner.
- Load code on demand: Components can load when users need them.
- Support large applications: Large applications can divide their code into smaller chunks.
- Improve navigation experiences: Pages can load their code as users navigate to them.
- Optimize resource usage: Code for less frequently used sections may not need to load immediately.
Important: Lazy loading can improve performance, but the actual benefit depends on the application, bundler, network conditions, and component size.
3. What Is React.lazy()?
React.lazy() is a function that allows you to define a component whose code is loaded dynamically when React first attempts to render it.
Syntax
import { lazy } from "react";
const MyComponent = lazy(() => import("./MyComponent"));
Explanation
lazy() defines a lazy-loaded component.
import("./MyComponent") dynamically imports the component module.
- The dynamic import returns a Promise.
- React waits for the Promise to resolve before rendering the loaded component.
- The imported module should provide the component as its default export for this pattern.
Declare lazy components outside your other component functions. Defining them inside a component can cause unexpected remounting and loss of local state.
4. What Is React Suspense?
Suspense is a React component that displays fallback UI while its children are waiting for supported content to become ready. For lazy-loaded components, it shows a loading message, spinner, or skeleton while the component's code is loading.
Syntax
import { Suspense } from "react";
<Suspense fallback={<p>Loading...</p>}>
<MyComponent />
</Suspense>
Important Props
| Prop |
Description |
children |
The content React attempts to render. |
fallback |
The placeholder UI displayed while the child is suspended. |
When the lazy-loaded component is ready, React replaces the fallback with the actual component UI.
5. Creating Your First Lazy-Loaded Component
Follow these steps to implement lazy loading in a React project.
Step 1: Create a Component
Create a file named About.jsx.
function About() {
return (
<div>
<h2>About Us</h2>
<p>Welcome to our React application.</p>
</div>
);
}
export default About;
Step 2: Import lazy and Suspense
In your main application file, import the required React APIs.
import { lazy, Suspense } from "react";
Step 3: Define the Lazy Component
const About = lazy(() => import("./About"));
Step 4: Wrap It in Suspense
import { lazy, Suspense } from "react";
const About = lazy(() => import("./About"));
function App() {
return (
<div>
<h1>My Website</h1>
<Suspense fallback={<p>Loading About page...</p>}>
<About />
</Suspense>
</div>
);
}
export default App;
How It Works
- The application initially renders its main content.
- React attempts to render the lazy-loaded About component.
- The dynamic import begins loading the component module.
- Suspense displays the fallback while the module is pending.
- After the module loads, React displays the About component.
6. Lazy Loading on User Interaction
You can combine lazy loading with state to load and display a component only when the user requests it.
import { lazy, Suspense, useState } from "react";
const Reports = lazy(() => import("./Reports"));
function App() {
const [showReports, setShowReports] = useState(false);
return (
<div>
<h1>Dashboard</h1>
<button onClick={() => setShowReports(true)}>
Open Reports
</button>
{showReports && (
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
)}
</div>
);
}
export default App;
Explanation:
- The Reports component is defined using
lazy().
- Initially,
showReports is false, so the component is not rendered.
- When the user clicks Open Reports, the state becomes
true.
- React attempts to render Reports, triggering its dynamic import if it has not already loaded.
- Suspense displays a loading message while the code is loading.
7. Lazy Loading Multiple Components
You can lazy-load multiple components to divide a large application into separate code chunks.
import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./Dashboard"));
const Reports = lazy(() => import("./Reports"));
const Settings = lazy(() => import("./Settings"));
function App() {
return (
<div>
<h1>Admin Panel</h1>
<Suspense fallback={<p>Loading section...</p>}>
<Dashboard />
<Reports />
<Settings />
</Suspense>
</div>
);
}
export default App;
In this example, each component is dynamically imported. However, because all three are rendered immediately inside the same Suspense boundary, React may need to wait for all suspended children before revealing the complete content within that boundary.
In a real application, consider rendering only the selected page or using separate Suspense boundaries when different sections should appear independently.
8. Lazy Loading with React Router
Lazy loading is commonly used with React Router so that page components can be loaded when users navigate to different routes.
Example
import { lazy, Suspense } from "react";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
const Contact = lazy(() => import("./pages/Contact"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
export default App;
Benefits:
- Page components can be split into separate chunks by a supporting bundler.
- Users do not need to download every route's component code as part of the initial page bundle.
- A common fallback can display while a destination route loads.
- Separate Suspense boundaries can be used for more specific loading experiences.
Note: This example uses React Router's standard routing components. For larger applications, route-level lazy loading can also be configured through router-specific APIs.
9. Lazy Loading with Nested Suspense Boundaries
Nested Suspense boundaries let different parts of a page show their own loading states instead of making the entire page wait for every lazy component.
import { lazy, Suspense } from "react";
const Profile = lazy(() => import("./Profile"));
const Activity = lazy(() => import("./Activity"));
function Dashboard() {
return (
<div>
<h1>User Dashboard</h1>
<Suspense fallback={<p>Loading profile...</p>}>
<Profile />
</Suspense>
<Suspense fallback={<p>Loading activity...</p>}>
<Activity />
</Suspense>
</div>
);
}
export default Dashboard;
Each Suspense boundary controls the fallback for its own content. The profile section can appear as soon as it is ready, without necessarily waiting for the activity section.
10. Lazy Loading vs. Regular Import
| Feature |
Regular Import |
Lazy Loading |
| Syntax |
import About from "./About" |
lazy(() => import("./About")) |
| Loading behavior |
Module is included in the normal static dependency graph. |
Module can be loaded on demand. |
| Code splitting |
Does not itself create a lazy loading boundary. |
Usually enables code splitting with a supporting bundler. |
| Fallback UI |
Not required for a normal static import. |
Use Suspense to display a fallback while loading. |
| Best use cases |
Core UI required immediately. |
Large pages, reports, admin panels, and less frequently used sections. |
11. Advantages of Lazy Loading Components
- Smaller initial JavaScript bundle: Code for deferred components can be separated from the initial bundle.
- Potentially faster initial load: The browser may need to download and process less JavaScript before the initial interface is usable.
- On-demand loading: Less frequently used features can load only when requested.
- Improved code organization: Large applications can be divided into manageable modules.
- Flexible loading UI: Suspense provides a clear way to display loading indicators.
- Useful for route-based applications: Individual pages can be loaded as users navigate.
12. Limitations of Lazy Loading
- Additional network requests: Deferred components may require extra requests when first opened.
- Visible loading delays: Users may see a fallback while a component downloads.
- Import failures: A failed dynamic import requires appropriate error handling.
- Setup considerations: The build tool or framework must support dynamic imports.
- Overuse can add complexity: Lazy-loading every small component may create unnecessary loading boundaries.
- Performance depends on context: Lazy loading is not automatically faster for every component or application.
13. Common Mistakes in Lazy Loading
Mistake 1: Forgetting Suspense
import { lazy } from "react";
const About = lazy(() => import("./About"));
function App() {
return <About />;
}
Problem: A lazy-loaded component needs a suitable Suspense boundary above it to display fallback UI while it is suspended.
Correction:
import { lazy, Suspense } from "react";
const About = lazy(() => import("./About"));
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<About />
</Suspense>
);
}
Mistake 2: Using a Named Export Without Adapting It
React.lazy() expects the imported module's resolved value to provide a valid component through its default property.
If a component is exported by name, adapt the import result.
// widgets.jsx
export function Chart() {
return <h2>Sales Chart</h2>;
}
// App.jsx
import { lazy } from "react";
const Chart = lazy(() =>
import("./widgets").then((module) => ({
default: module.Chart
}))
);
Mistake 3: Declaring lazy() Inside a Component
function App() {
// Avoid defining lazy components here.
const About = lazy(() => import("./About"));
return <About />;
}
Correction: Declare the lazy component at the module's top level to avoid unexpected component remounting and state resets.
Mistake 4: Assuming Suspense Catches Every Error
Suspense handles supported suspended rendering states, such as a lazy component waiting for its module to load. It is not a general-purpose error handler. Use an Error Boundary to handle rendering errors, including rejected lazy imports that React throws to the nearest Error Boundary.
14. Handling Lazy Loading Errors
A dynamic import can fail because of a network problem or an unavailable JavaScript chunk. You can combine lazy loading with an Error Boundary to display a useful error message.
Error Boundary Component
import React from "react";
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return (
<div role="alert">
<h2>Unable to load this section.</h2>
<p>Please try again later.</p>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
Using Error Boundary and Suspense Together
import { lazy, Suspense } from "react";
import ErrorBoundary from "./ErrorBoundary";
const Reports = lazy(() => import("./Reports"));
function App() {
return (
<ErrorBoundary>
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
</ErrorBoundary>
);
}
export default App;
How it works: Suspense displays the loading fallback while the module is pending. If the lazy import rejects and React throws the error, the Error Boundary can display its fallback UI.
15. Best Practices for Lazy Loading
- Use lazy loading for large or less frequently used components.
- Declare lazy components outside other component functions.
- Place Suspense boundaries where the loading indicator should appear.
- Choose useful fallback UI, such as a spinner, skeleton, or short loading message.
- Use Error Boundaries to handle rejected lazy imports and other supported rendering errors.
- Consider route-level code splitting in applications with many pages.
- Avoid lazy loading tiny components when the overhead outweighs the benefit.
- Test loading and failure states under slow or unreliable network conditions.
- Measure bundle size and runtime performance instead of assuming every change improves speed.
16. Practical Project: Lazy-Loaded Reports Page
Project objective: Build a dashboard that loads its Reports component only when the user opens the reports section.
Reports.jsx
function Reports() {
return (
<div>
<h2>Monthly Reports</h2>
<p>Your monthly performance report is ready.</p>
</div>
);
}
export default Reports;
App.jsx
import { lazy, Suspense, useState } from "react";
const Reports = lazy(() => import("./Reports"));
function App() {
const [showReports, setShowReports] = useState(false);
return (
<div>
<h1>Business Dashboard</h1>
<p>View your dashboard and reports.</p>
<button onClick={() => setShowReports(true)}>
View Reports
</button>
{showReports && (
<Suspense fallback={<p>Preparing your reports...</p>}>
<Reports />
</Suspense>
)}
</div>
);
}
export default App;
Expected Result
- The dashboard heading appears immediately.
- The Reports component is not rendered initially.
- The user clicks View Reports.
- React loads the Reports module if it has not been loaded already.
- The fallback appears while the module is pending.
- The monthly report appears once the component is ready.
Practice Tasks
- Add a Settings component and load it only when the user clicks a button.
- Create separate Suspense boundaries for Reports and Settings.
- Wrap each lazy-loaded section with an Error Boundary.
- Compare the initial bundle with and without code splitting using your build tool's analysis features.
17. React Lazy Loading Interview Questions and Answers
Q1. What is lazy loading in React?
Lazy loading delays loading a component's code until it is needed, which can reduce the initial JavaScript bundle size.
Q2. Which function is used for lazy loading?
React provides the lazy() function.
Q3. What is the purpose of Suspense?
Suspense displays fallback UI while supported child content, such as a lazy-loaded component, is waiting to become ready.
Q4. What is dynamic import?
Dynamic import() loads a module asynchronously and returns a Promise.
Q5. Does React.lazy() work with named exports directly?
Not directly. The imported module must resolve to an object with a valid component in its default property. A named export can be adapted using then().
Q6. Where should lazy components be declared?
Declare them at the top level of a module, outside component functions.
Q7. Can lazy loading improve application performance?
Yes. It can reduce the initial bundle size and defer loading code until needed, but the actual improvement depends on the application and network conditions.
Q8. What happens if a lazy import fails?
The import Promise rejects. React throws the rejection reason during rendering so that the nearest Error Boundary can handle it.
Q9. Can we lazy-load pages in React Router?
Yes. Route components can be lazy-loaded and wrapped in Suspense to provide loading UI during navigation.
Q10. What is the difference between lazy loading and code splitting?
Code splitting divides an application's code into separate bundles or chunks. Lazy loading defers loading a component or resource until it is needed. They are often used together.
18. Quick Revision Checklist
- Understand the meaning and benefits of lazy loading.
- Know how to use
lazy() with dynamic imports.
- Understand how Suspense provides fallback UI.
- Practice lazy loading with user interactions and routes.
- Know how to use nested Suspense boundaries.
- Understand default exports and named export adaptation.
- Use Error Boundaries for lazy import failures.
- Learn when lazy loading is beneficial and when it may be unnecessary.
19. Official React Documentation
Refer to the official React documentation for detailed explanations and examples.
20. React JS Training at JustAcademy
Learn React JS concepts, component development, JSX, props, state, hooks, lazy loading, code splitting, and practical application development through React JS training.
Explore JustAcademy React JS Training
Want to learn more about the course structure and training approach? Register for a course demo.
Register for React JS Course Demo
Conclusion
Lazy Loading Components is a useful React technique for deferring component code until it is needed. By combining lazy(), dynamic imports, and Suspense, developers can build applications that load code on demand and provide helpful loading states. When combined with route-based code splitting, sensible fallback UI, and Error Boundaries, lazy loading can help create more efficient and maintainable React applications.