Code Splitting
Learn how to divide a React application's JavaScript into smaller chunks, load code when required, and improve the initial loading experience using dynamic imports and React.lazy.
1. Introduction to Code Splitting
Code splitting is a technique that divides an application's JavaScript code into smaller files called chunks. Instead of downloading all application code at once, the browser can load the chunks required for the current page and load other chunks when they are needed.
As a React application grows, it may contain many features such as dashboards, reports, student management, settings, and authentication. Loading every feature's code immediately can increase the amount of JavaScript needed during the initial load.
Code splitting helps organize the application's code into smaller loading units. It is commonly implemented through dynamic imports and supported by build tools such as Vite and webpack.
2. Understanding Code Splitting with a Diagram
Without code splitting, an application may place most of its JavaScript into one large initial bundle. With code splitting, the application can load a smaller initial bundle and separate feature chunks when required.
Without Code Splitting
Multiple features may be included in the initial JavaScript bundle.
With Code Splitting
Additional feature chunks can be loaded when the application needs them.
3. Why Do We Need Code Splitting?
Smaller Initial Download
The browser may download less JavaScript before displaying the initial screen.
On-Demand Features
Features that are not immediately needed can be loaded when the user opens them.
Better Organization
Separate chunks can correspond to different pages, features, or dependencies.
Performance Optimization
Smaller initial downloads can help improve loading performance, depending on the application and network.
4. Static Imports and Dynamic Imports
Static imports are commonly used for modules that are required by a component. Dynamic imports allow a module to be requested asynchronously and can create a code-splitting point in supported build tools.
import Reports from './Reports';
export default function App() {
return (
<div>
<h1>Student Dashboard</h1>
<Reports />
</div>
);
}
import('./Reports')
.then((module) => {
console.log('Reports module loaded');
console.log(module.default);
})
.catch((error) => {
console.error('Unable to load Reports', error);
});
The dynamic import returns a Promise that resolves to the module. Build tools can use this import to create a separate chunk. The code above demonstrates module loading; React.lazy is the usual approach when rendering a lazily loaded React component.
5. Implementing Code Splitting with React.lazy
React.lazy allows a component to be loaded through a dynamic import when React first attempts to render it. Suspense provides fallback content while the component's module is loading.
export default function Reports() {
return (
<div>
<h2>Reports Page</h2>
<p>View student performance reports.</p>
</div>
);
}
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 Open Reports is clicked, the state changes.
- React attempts to render Reports and requests its module if it has not loaded yet.
- Suspense can display Loading reports while the module is loading.
- When the module becomes available, React displays the Reports component.
6. Code Splitting with React Router
Large applications often contain multiple routes. Route-based code splitting allows page components to be loaded when users navigate to the corresponding routes.
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'));
const Settings = lazy(() => import('./pages/Settings'));
export default function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
{' | '}
<Link to="/reports">Reports</Link>
{' | '}
<Link to="/settings">Settings</Link>
</nav>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/reports"
element={<Reports />}
/>
<Route
path="/settings"
element={<Settings />}
/>
</Routes>
</Suspense>
</BrowserRouter>
);
}
Here, Home, Reports, and Settings are declared as lazy-loaded components. A build tool that supports dynamic-import splitting can generate separate chunks for these modules.
7. Understanding Suspense and Loading States
When a lazy-loaded component is requested, the browser may need time to download and evaluate its JavaScript. Suspense allows React to display fallback content while the component is waiting to load.
import { lazy, Suspense } from 'react';
const StudentDetails = lazy(
() => import('./StudentDetails')
);
export default function LoadingFallback() {
return (
<div>
<h2>Student Management</h2>
<Suspense
fallback={
<div className="loading-message">
Loading student details...
</div>
}
>
<StudentDetails />
</Suspense>
</div>
);
}
The fallback is displayed while the lazy component is waiting for its module. After the module loads successfully, React renders the StudentDetails component.
8. Code Splitting vs Lazy Loading
| Feature | Code Splitting | Lazy Loading |
|---|---|---|
| Meaning | Dividing application code into separate chunks. | Deferring loading until the resource or component is needed. |
| Purpose | Creates smaller loading units. | Controls when selected code is requested. |
| React support | Usually configured through dynamic imports and build tools. | React.lazy and Suspense support lazy component rendering. |
| Common use | Separating large application features. | Loading a feature when a user opens it. |
| Relationship | Creates opportunities to load chunks separately. | Can use those chunks on demand. |
9. Common Mistakes
- Splitting every small component: Too many tiny chunks can introduce additional network overhead.
- Forgetting Suspense: Lazy-loaded components need an appropriate Suspense boundary.
- Missing default exports: React.lazy expects the imported module's default export to be the component.
- Ignoring loading feedback: Provide useful fallback content while chunks load.
- Ignoring import failures: Provide an appropriate error-handling strategy for failed chunk requests.
- Assuming total code size decreases: Code splitting changes bundle organization and loading behavior, not necessarily total code size.
10. Best Practices
- Split large features that are not required for the initial screen.
- Use route-based code splitting for applications with many pages.
- Use meaningful Suspense fallback content.
- Keep lazy component declarations outside the rendering component.
- Handle loading failures appropriately.
- Measure bundle sizes and loading performance before and after changes.
11. Practice Tasks
- Create Home, Reports, and Settings page components.
- Import the pages normally and observe the application's build output.
- Convert the page imports to React.lazy and use Suspense.
- Configure route-based loading with React Router.
- Display a fallback message while a page chunk loads.
- Compare the initial bundle and generated chunks using your build tool's output.
Summary
Code splitting divides an application's JavaScript into smaller chunks so that the initial screen does not always need every feature's code. Dynamic imports and supported build tools create opportunities for separate chunks, while React.lazy and Suspense help load components when they are required and display fallback content during loading. Route-based splitting, meaningful loading states, appropriate error handling, and performance measurement help developers apply code splitting effectively.