| How to Reduce React App Bundle Size :👈 | 👉:How to Use Suspense and Lazy Loading |
Code Splitting and Lazy Loading in React |
Code Splitting and Lazy Loading in React
1. What Is Code Splitting?
Code splitting is a technique used to divide a large JavaScript bundle into smaller chunks that can be loaded separately.
In a typical React application, the build tool bundles JavaScript files, components, and dependencies into production assets.
If the application contains multiple pages, all their code may be included in the initial bundle unless code splitting is configured.
Example: Consider an application with the following pages:
- Home
- Products
- Orders
- Reports
- Settings
Without Code Splitting
The initial bundle may contain code for all these pages, even though the user initially visits only the Home page.
With Code Splitting
Now the application can download the JavaScript required for each page when the user visits it.
Benefits of Code Splitting
- Reduces initial JavaScript download size.
- Improves initial page loading performance.
- Avoids loading code that the user may never need.
- Helps organize large applications into smaller chunks.
- Can improve performance on slower networks and mobile devices.
2. What Is Lazy Loading?
Lazy loading is a technique in which a resource or component is loaded only when it is needed.
Instead of loading all components when the application starts, React can load certain components dynamically when they are first required.
Example:
Suppose an application has a Reports page containing a large charting library.
The user may visit the Home page frequently but rarely visit Reports.
There is no need to load the charting library immediately when the application starts.
Load the Reports page and its charting code only when the user navigates to Reports.
Benefits of Lazy Loading
- Loads components only when required.
- Reduces unnecessary initial downloads.
- Improves initial application loading.
- Useful for large pages and optional features.
- Helps applications with many routes and dependencies.
3. Difference Between Code Splitting and Lazy Loading
| Feature | Code Splitting | Lazy Loading |
|---|---|---|
| Meaning | Divides a large bundle into smaller chunks. | Delays loading until a resource is needed. |
| Purpose | Creates separate JavaScript chunks. | Controls when resources are loaded. |
| Loading | Chunks can be loaded independently. | Loads resources on demand. |
| React support | Dynamic imports and build-tool support. | React.lazy and Suspense for components. |
| Example | Separate Home, Products, and Reports bundles. | Load Reports only when the user opens it. |
Simple explanation: Code splitting creates smaller bundles, while lazy loading determines when those bundles are downloaded and used.
4. How to Implement Code Splitting in React
JavaScript supports dynamic imports using the import() function.
A dynamic import returns a Promise that resolves to the imported module.
Static Import
import Reports from "./pages/Reports";
This imports the module when the containing JavaScript module is loaded.
Dynamic Import
const reportsPromise = import("./pages/Reports");
This requests the module dynamically when the import() expression executes.
Build tools such as Vite and Webpack can use dynamic imports as code-splitting boundaries and generate separate chunks.
5. React.lazy and Suspense
React provides two important features for component-level lazy loading:
- React.lazy: Dynamically imports a component.
- Suspense: Displays fallback content while the component is loading.
Basic Syntax
import React, { lazy, Suspense } from "react";
const Reports = lazy(() => import("./pages/Reports"));
function App() {
return (
<Suspense fallback={<p>Loading Reports...</p>}>
<Reports />
</Suspense>
);
}
export default App;
How It Works
- React.lazy defines a component that will be loaded dynamically.
- React attempts to render the component.
- The dynamic import starts loading the JavaScript module.
- While the module is loading, Suspense displays its fallback.
- When the module loads successfully, React displays the component.
Important: React.lazy expects the dynamically imported module to provide a default export.
6. Practical Example: Route-Based Code Splitting
Route-based code splitting is one of the most common ways to optimize large React applications.
Consider an application with three pages:
- Home
- Products
- Reports
Project Structure
src/ | +---- pages/ | | | +---- Home.jsx | +---- Products.jsx | +---- Reports.jsx | +---- App.jsx +---- main.jsx
Home.jsx
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the application.</p>
</div>
);
}
export default Home;
Products.jsx
function Products() {
return (
<div>
<h2>Products Page</h2>
<p>Display available products.</p>
</div>
);
}
export default Products;
Reports.jsx
function Reports() {
return (
<div>
<h2>Reports Page</h2>
<p>Display application reports.</p>
</div>
);
}
export default Reports;
App.jsx - Lazy Loading with React Router
import React, { lazy, Suspense } from "react";
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
const Home = lazy(() => import("./pages/Home"));
const Products = lazy(() => import("./pages/Products"));
const Reports = lazy(() => import("./pages/Reports"));
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> |
<Link to="/products">Products</Link> |
<Link to="/reports">Reports</Link>
</nav>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route
path="/"
element={<Home />}
/>
<Route
path="/products"
element={<Products />}
/>
<Route
path="/reports"
element={<Reports />}
/>
</Routes>
</Suspense>
</BrowserRouter>
);
}
export default App;
What happens?
| User Action | What React Loads |
|---|---|
| Opens Home | Home page chunk |
| Opens Products | Products page chunk |
| Opens Reports | Reports page chunk |
The application does not need to download all three page components as part of the initial page bundle.
7. Lazy Load Heavy Components
Lazy loading is not limited to pages. It can also be applied to large components within a page.
For example, consider a Dashboard containing:
- Dashboard summary
- Recent activities
- Large charts
- Detailed analytics
The summary and recent activities may be needed immediately, while detailed analytics may be optional.
Example
import React, {
lazy,
Suspense,
useState
} from "react";
const Analytics = lazy(
() => import("./Analytics")
);
function Dashboard() {
const [showAnalytics, setShowAnalytics] = useState(false);
return (
<div>
<h2>Dashboard</h2>
<p>Dashboard summary</p>
<button
onClick={() => setShowAnalytics(true)}
>
View Analytics
</button>
{showAnalytics && (
<Suspense fallback={<p>Loading analytics...</p>}>
<Analytics />
</Suspense>
)}
</div>
);
}
export default Dashboard;
In this example:
- The Dashboard loads first.
- The Analytics component is not initially rendered.
- When the user clicks View Analytics, React attempts to render Analytics.
- The dynamic import loads the component.
- Suspense displays a loading message until the component is ready.
8. Lazy Loading Third-Party Libraries
Some third-party libraries are large and may not be required immediately.
Examples include:
- PDF generation libraries.
- Excel export libraries.
- Charting libraries.
- Rich text editors.
- Large data visualization libraries.
Instead of importing these libraries at the top level, use dynamic imports.
Example: Load jsPDF Only When Required
async function generatePDF() {
const { jsPDF } = await import("jspdf");
const doc = new jsPDF();
doc.text("Application Report", 10, 10);
doc.save("report.pdf");
}
function App() {
return (
<button onClick={generatePDF}>
Download PDF
</button>
);
}
export default App;
The jsPDF library is requested only when the user clicks the Download PDF button.
9. Suspense Fallback and Loading Indicators
When a lazy-loaded component is downloading, React needs to display something to the user.
Suspense provides a fallback property for this purpose.
Example
<Suspense fallback={<p>Loading...</p>}>
<Reports />
</Suspense>
You can use a simple message, spinner component, or skeleton UI.
Example with a Loading Component
function Loading() {
return (
<div>
<p>Please wait, loading content...</p>
</div>
);
}
function App() {
return (
<Suspense fallback={<Loading />}>
<Reports />
</Suspense>
);
}
A meaningful loading indicator improves the user experience, particularly when network connections are slow.
10. Error Handling for Lazy-Loaded Components
Lazy-loaded components can fail to load because of network problems, missing files, or deployment issues.
Suspense handles the loading state, but it does not handle errors. Use a React Error Boundary to display a fallback when a lazy import fails.
Example
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error) {
return {
hasError: true
};
}
render() {
if (this.state.hasError) {
return <p>Unable to load this page.</p>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Use the Error Boundary together with Suspense:
import React, { lazy, Suspense } from "react";
import ErrorBoundary from "./ErrorBoundary";
const Reports = lazy(() => import("./pages/Reports"));
function App() {
return (
<ErrorBoundary>
<Suspense fallback={<p>Loading Reports...</p>}>
<Reports />
</Suspense>
</ErrorBoundary>
);
}
Now the application can show a loading message while the component loads and an error message if loading fails.
Note: An Error Boundary does not automatically retry a failed dynamic import. Retry behavior requires additional logic, and some module-loading failures may require a page reload.
11. Where Should You Apply Code Splitting?
Not every component needs lazy loading. Apply it where it provides a meaningful performance benefit.
| Application Area | Recommended Approach |
|---|---|
| Home page | Usually load immediately. |
| Products page | Route-based lazy loading. |
| Reports page | Route-based lazy loading. |
| Admin module | Lazy load when users navigate to it. |
| PDF export | Dynamic import when export is requested. |
| Large charts | Lazy load when charts are needed. |
| Rich text editor | Lazy load when editing is requested. |
| Frequently used navigation | Consider preloading to avoid navigation delays. |
12. Prefetching and Preloading
Lazy loading reduces unnecessary downloads, but waiting until a user clicks a link can sometimes introduce a loading delay.
Prefetching and preloading can help balance this trade-off.
Prefetching: Downloads resources that may be needed in the near future, often when the browser is idle.
Preloading: Requests important resources earlier because they are expected to be needed soon.
Example using a dynamic import to start loading a page when the user is likely to navigate to it:
function preloadReports() {
import("./pages/Reports");
}
function Navigation() {
return (
<button
onMouseEnter={preloadReports}
onFocus={preloadReports}
>
Reports
</button>
);
}
The dynamic import starts loading the Reports module when the user hovers over or focuses on the button.
Note: Prefetching and preloading strategies should be used selectively. Loading too many resources early can increase network usage and compete with critical resources.
13. Common Mistakes in Code Splitting and Lazy Loading
Mistake 1: Lazy Loading Every Component
Lazy loading every small component can create unnecessary complexity and loading transitions.
Better approach: Apply it mainly to routes, large components, and optional features.
Mistake 2: Forgetting Suspense
React.lazy components must be rendered inside an appropriate Suspense boundary.
Better approach: Provide a useful fallback such as a loading indicator or skeleton.
Mistake 3: Using Named Exports Directly with React.lazy
React.lazy expects a module with a default export.
For a named export, adapt it using a Promise:
const Reports = lazy(() =>
import("./pages/Reports").then(module => ({
default: module.Reports
}))
);
Here, Reports is a named export from the module.
Mistake 4: Loading All Lazy Components Immediately
If all lazy-loaded components are rendered immediately, they will all be requested.
Better approach: Use conditional rendering or route-based loading so components are loaded when needed.
Mistake 5: Ignoring Loading Errors
Network failures can prevent a chunk from loading.
Better approach: Use Error Boundaries and provide a suitable recovery option.
14. Best Practices
- Use route-based code splitting for large applications.
- Use React.lazy for suitable components.
- Wrap lazy-loaded components in Suspense.
- Lazy load large third-party libraries.
- Load optional features only when required.
- Provide useful loading indicators.
- Use Error Boundaries for loading failures.
- Consider prefetching frequently accessed routes.
- Avoid splitting every small component.
- Analyze production bundles to verify the generated chunks.
- Measure initial loading performance before and after optimization.
15. Interview Questions and Answers
Q1. What is code splitting in React?
Code splitting is a technique that divides a large JavaScript bundle into smaller chunks so that the application can load only the required code when needed.
Q2. What is lazy loading?
Lazy loading is a technique that delays loading a component or resource until it is required.
Q3. What is React.lazy?
React.lazy allows a component to be loaded dynamically using the import() function. It is commonly used for route-based and component-level lazy loading.
Q4. What is Suspense?
Suspense allows React to display fallback content while a supported child resource, such as a lazy-loaded component, is loading.
Q5. What is the difference between React.lazy and Suspense?
React.lazy defines a dynamically loaded component. Suspense provides fallback UI while that component is loading.
Q6. Can we lazy load React routes?
Yes. React.lazy can be combined with React Router to load page components when users navigate to specific routes.
Q7. Can we lazy load third-party libraries?
Yes. JavaScript dynamic imports can load third-party libraries only when a feature requires them.
Q8. Does lazy loading reduce the total bundle size?
Not necessarily. It primarily reduces the amount of JavaScript downloaded initially by moving code into separately loaded chunks. The total JavaScript across all chunks may remain similar.
Q9. What happens if a lazy-loaded component fails to load?
The loading Promise rejects. Suspense does not handle this error. A React Error Boundary can catch the rendering error and display fallback UI.
Q10. When should you avoid lazy loading?
Avoid lazy loading components that are very small, essential for the initial screen, or frequently needed immediately. Lazy loading can introduce additional network requests and visible loading delays.
16. Quick Summary
| Concept | Purpose |
|---|---|
| Code Splitting | Divide a large JavaScript bundle into smaller chunks. |
| Lazy Loading | Load resources only when required. |
| Dynamic import() | Load JavaScript modules asynchronously. |
| React.lazy | Define dynamically loaded React components. |
| Suspense | Display fallback UI while a lazy component loads. |
| Error Boundary | Handle errors during component loading and rendering. |
| Prefetching | Load resources that may be needed soon. |
| Route-based splitting | Load page components when users navigate to them. |
Key takeaway: Code splitting divides a large React application into smaller chunks, while lazy loading ensures that those chunks are downloaded only when required. Use React.lazy, Suspense, and dynamic imports to reduce initial JavaScript loading and improve application startup performance.
| How to Reduce React App Bundle Size :👈 | 👉:How to Use Suspense and Lazy Loading |
Comments and Discussion