How to Implement Code Splitting
Load only the JavaScript a route needs, defer the rest, and prefetch the next chunk so a split never costs a delay.
On this page
Introduction
A single bundle means every page loads the code for every page, including the routes the user will never visit. Code splitting divides the bundle into chunks loaded on demand, so the initial download carries only what the first screen needs. Done well, it reduces the time to interactive; done carelessly, it adds a waterfall of late-loaded chunks that delays the very interaction it was meant to speed up. This article covers route-based splitting, dynamic imports, prefetching the next chunk, and how to keep splitting from creating a request waterfall.
Why Split
Every byte in the initial bundle must be downloaded, parsed and executed before the page is interactive, and the cost is per-visit regardless of which route the user takes. A route that is visited rarely still taxes every visit if its code is in the main bundle. Splitting moves that code to a chunk that loads only when the route is opened.
The benefit is largest for a large app with distinct routes and heavy optional features, such as an editor or a chart library used on one page. A small app may not benefit, because splitting adds a request and the total code may be tiny; measure before splitting.
Route-Based Splitting
The most natural boundary is the route: each route becomes a chunk, and the initial bundle contains the shared shell plus the first route. A router that supports lazy routes loads the chunk when the route is matched, which aligns the split with how users navigate.
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
// Each import() becomes a chunk loaded when the route is first visited.
const Home = lazy(() => import('./routes/Home'));
const Dashboard = lazy(() => import('./routes/Dashboard'));
const Settings = lazy(() => import('./routes/Settings'));
export function App() {
return (
<Suspense fallback={<Spinner />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
Dynamic Import for Heavy Features
Not every split is a route. A heavy feature used on one page, such as a rich text editor or a chart library, can be split even within a route: import it only when the user opens the feature. This keeps it out of the route’s initial chunk as well, so the route loads fast and the heavy code arrives when it is needed.
import { lazy, Suspense, useState } from 'react';
// The editor (and its dependencies) loads only when the user opens it.
const Editor = lazy(() => import('./Editor'));
function Composer() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(true)}>Write a post</button>
{open && (
<Suspense fallback={<Spinner />}>
<Editor />
</Suspense>
)}
</div>
);
}
Prefetching What Comes Next
A split chunk loads on demand, which adds a round trip before the code is available. To avoid the user waiting, prefetch the chunk the user is likely to need next: on a link hover, on idle, or right after the current route renders. The network request happens while the user is reading or deciding, so the chunk is ready when the navigation happens.
Prefetch on a hint rather than for everything, because prefetching all chunks is the same as not splitting them. Prefetch the next likely route and the heavy feature on the page, and let the rest load on demand. This keeps the benefit of splitting while removing the delay for the common navigation.
Splitting Vendors
Vendor code changes less often than application code, so splitting the two lets the browser cache the vendor chunk across deploys and re-download only the app chunk. A bundler can extract the vendor chunk, but splitting too finely into many small vendor chunks adds requests and can be worse. Group the major libraries into a few chunks that change on different schedules.
Splitting a lazy route into shared and route-specific chunks also helps: a library used by two routes should go into a shared chunk both can reuse, rather than being duplicated into each route chunk. Check the build output to see whether a dependency is duplicated across chunks, which is a sign the split is misplaced. The bundler can report the chunk graph, and a dependency that appears in more than one chunk is either intentionally shared or a mistake worth fixing.
Measuring the Effect
Measure the initial bundle size and the time to interactive before and after, and watch the number of requests on first load. A split that reduces the initial bundle but adds three late requests that block the first interaction has not helped. Use the browser’s coverage and network panels to see what loads and when, and measure on a throttled connection rather than a fast one, because the split is meant to improve the slow case.
Set a budget for the initial bundle and check it in the pipeline, so a new dependency that lands in the main chunk is caught. The budget is what keeps splitting from decaying as features are added, because without it the main bundle grows until the split no longer matters.
Conclusion
Code splitting loads only what a route or feature needs, reducing the initial bundle and the time to interactive. Split by route for the natural boundaries and by heavy feature for the expensive optional code, prefetch the next likely chunk on a hint so the split does not add a delay, and group vendors and shared code into chunks that change on different schedules. Measure the initial bundle and the request waterfall on a throttled connection, and set a budget so a new heavy dependency cannot quietly rejoin the main chunk. Then the first screen loads fast and the rest arrives when it is needed.
Sources: React: lazy, web.dev: Code splitting, Vite: build options and chunks.
FAQ
- Does code splitting always make a page faster?
- No. It reduces the initial bundle but adds a request for each chunk, and a chunk loaded at the moment of interaction can delay it. Prefetch the next likely chunk so the split does not cost a round trip, and measure the time to interactive rather than the bundle size alone.
- Why split vendor code from application code?
- Vendor code changes less often, so a separate chunk can be cached across application deploys and only the app chunk re-downloaded. Split too finely and you add requests; group major libraries into a few chunks that change on different schedules.
Report a problem with this articleOpens a pre-filled issue on GitHub.