Code splitting is the rare optimization where the trade is almost entirely in your favor: the browser downloads less before the first paint, and the only cost is a small amount of coordination for the code that arrives later. The complication is that a bundle is a graph, not a bag. Split one component and every module it imports moves with it, including the shared utilities and vendor libraries that other parts of the page also need, so a naive split can produce a page that downloads the same library twice in two chunks.
âĄThe unit of splitting is a dependency subtree
When you mark a module for lazy loading, the bundler walks everything reachable from it. If that subtree includes a charting library only this page uses, excellent. If it also includes your shared design system, then every other chunk that needs those components will carry its own copy unless the bundler is told to extract them.
What a dynamic import tells the bundler
A static import says: this code is needed wherever this module is needed, so include it in the current chunk. A dynamic import says: this code is needed at some point in the future, so create a separate file and fetch it when the expression runs. The bundler takes it from there, cutting the graph at that boundary and emitting a new chunk containing everything reachable only from the lazy side.
The practical consequences follow immediately. The cut point is the import expression, so the split happens exactly where you wrote it. Chunks are shared, so two lazy routes that both depend on the same library will resolve that library to a common chunk fetched once. And because a dynamic import returns a promise, it fits naturally into React's Suspense model, where the boundary's fallback is shown while the chunk loads. Static analysis cannot guess that you meant to defer something, so nothing is split until you say so explicitly.
Route-level splitting done right
Most applications should begin and often end here. Each page becomes its own chunk, the navigation stays in the initial bundle so links are immediately clickable, and the cost of a page a visitor never opens is never paid.
import { lazy, Suspense, useEffect } from 'react';
import { BrowserRouter, Routes, Route, NavLink, useNavigate } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const Catalogue = lazy(() => import('./routes/Catalogue'));
const Product = lazy(() => import('./routes/Product'));
const Account = lazy(() => import('./routes/Account'));
function RouteFallback() {
return (
<div className="route-fallback" role="status" aria-live="polite">
<span className="skeleton-line" />
<span className="skeleton-line short" />
</div>
);
}
export default function App() {
return (
<BrowserRouter>
<SiteNav />
<Suspense fallback={<RouteFallback />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/catalogue" element={<Catalogue />} />
<Route path="/product/:id" element={<Product />} />
<Route path="/account/*" element={<Account />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
function SiteNav() {
const navigate = useNavigate();
useEffect(() => {
const warm = () => import('./routes/Catalogue');
const idle = window.requestIdleCallback || ((fn) => setTimeout(fn, 1500));
idle(warm);
}, []);
return (
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/catalogue">Catalogue</NavLink>
<NavLink to="/account">Account</NavLink>
<button onClick={() => navigate('/product/p-1024')}>Featured</button>
</nav>
);
}
The fallback deserves attention because it is what the visitor actually sees. A full-screen spinner for a route that loads in ninety milliseconds causes a flash; a skeleton shaped like the destination content lets the layout settle once. Size the fallback to roughly the final height, and the swap produces no cumulative layout shift.
Splitting a heavy widget and its dependency
Not every split is a route. A rich text editor, a map, a spreadsheet grid or a diagram renderer can outweigh the rest of the page combined, and it usually appears behind an interaction: opening a modal, expanding a panel, clicking an edit button. Splitting at that interaction removes the cost from every session that never triggers it.
import { Suspense, lazy, useState, useEffect } from 'react';
const DiagramEditor = lazy(() =>
import(/* webpackChunkName: "diagram-editor" */ './DiagramEditor')
);
export function DocumentView({ document }) {
const [editing, setEditing] = useState(false);
useEffect(() => {
function onFocus() {
import('./DiagramEditor');
}
window.addEventListener('focus', onFocus, { once: true });
return () => window.removeEventListener('focus', onFocus);
}, []);
if (!editing) {
return (
<article>
<h1>{document.title}</h1>
<div dangerouslySetInnerHTML={{ __html: document.body }} />
<button onClick={() => setEditing(true)}>Edit diagram</button>
</article>
);
}
return (
<Suspense fallback={<div className="editor-skeleton" role="status">Loading editor...</div>}>
<DiagramEditor document={document} onExit={() => setEditing(false)} />
</Suspense>
);
}
Two techniques appear in that example. The chunk name comment gives the emitted file a stable identity, which makes size reports readable between builds instead of a wall of hashes. The warm-up on window focus starts the request during a moment when the main thread is idle, so if the person does click edit, the chunk is likely already in the cache.
Chunk shapes: what you are trading
Every split moves bytes between categories, and the categories matter more than the total.
| Strategy | Initial payload | Requests on first load | Risk |
|---|---|---|---|
| Single bundle | Largest | Fewest | Everyone downloads every feature |
| Route splitting | Small | One extra chunk per visited route | Fallback flash if the chunk is slow |
| Feature splitting | Smallest | Extra chunks only on interaction | More boundaries to reason about |
| Vendor extraction | Moderate and cacheable | Stable vendor chunk plus app chunk | A vendor upgrade busts the largest cache entry |
| Shared chunk extraction | Moderate | Common chunk loaded once | Overlapping groups can produce tiny orphan files |
The failure mode to watch is over-splitting. Twenty chunks of twelve kilobytes each cost twenty round trips, and on a high latency connection the request overhead outweighs the bytes saved. Group by how the code is actually used, keep the initial set to a handful of files, and prefer fewer, larger lazy chunks over a fine-grained cloud of them.
Prefetching so the split is invisible
A split you can feel is a regression in experience even if the numbers improved. The fix is to start loading before the click: on hover for pointers, on touchstart for touch devices, on route mount for the next likely destination, and in an idle callback for warm-up work that has no trigger. Each of these is a bet about intent, and the cost of a wrong bet is bandwidth rather than correctness.
Prefetch with the same conditions the real navigation will use, or you will cache a chunk under one query and fetch it again under another. And always guard against doing the work twice: a flag per module is enough, because repeated prefetches are invisible to the user and visible in your network panel. Treat prefetch as a hint rather than a promise, so a slow connection still works when the hint never fired.
Measuring the win
Report the numbers on every pull request that changes a boundary: initial kilobytes, number of initial requests, the weight of the heaviest lazy chunk, and the time from click to interactive for a cold navigation of the route you just split. The last figure is the one that justifies the work, because a page that loads in six hundred milliseconds after a split is only an improvement if it took longer before.
Check the sizes of the vendor and shared chunks too. A split that moves a shared library into two separate chunks has quietly made the page heavier for every visitor, and the only way to notice is a diff of the chunk report against the previous build. Track the number of initial requests alongside the bytes, because a page that trims forty kilobytes while adding five round trips can come out slower on a connection where latency dominates transfer time.
Common Mistakes
Splitting at a boundary that pulls a shared design system into several chunks
Fix: Inspect the chunk graph and extract shared modules so each library ships exactly once.
Showing a full-screen spinner for a chunk that arrives in under a hundred milliseconds
Fix: Size the fallback to the final layout so the swap produces no flash and no layout shift.
Splitting into dozens of tiny chunks to minimize each file
Fix: Group by real usage so the request count stays small, especially on high latency connections.
Declaring success without comparing the chunk report to the previous build
Fix: Post the size delta on the pull request and verify that no shared dependency duplicated.
Best Practices
- Split at route boundaries first, then at interaction boundaries for genuinely heavy widgets
- Give chunks stable names so size reports are comparable across builds
- Prefetch on hover, touch and idle so navigation feels immediate after the split
- Keep a small number of larger lazy chunks rather than a fine-grained cloud of files
Key Takeaways
- A dynamic import cuts the dependency graph at the expression you wrote and emits a chunk for everything reachable only from that side
- Because chunks are shared, splitting can duplicate a library unless shared modules are extracted deliberately
- Fallbacks must be shaped like the content they replace or the swap introduces layout shift
- Prefetching on intent converts the latency of a split into bandwidth spent on a bet that is usually right
- Measure click to interactive and the chunk diff on every change, because request overhead can outweigh saved bytes