Sub topic 12
Common pitfalls and measuring the result
This chapter closes the tutorial. It covers the mistakes that cancel out the benefit of code splitting, and how to check with measurements that your changes helped. It assumes you have read the earlier chapters on React.lazy, Suspense boundaries, error boundaries, transitions and preloading. You should also be comfortable reading a bundler build report and the browser DevTools Network panel.
Why splitting can backfire
Code splitting trades one large download for several smaller ones. That trade pays off only when the deferred code is not needed at startup, and when the extra requests do not add more delay than they remove. Most problems come from breaking one of those two conditions. Others come from how React treats lazy components.
| Pitfall | Symptom | Fix |
|---|---|---|
| `lazy` called inside a component | Spinner reappears, state is lost | Declare lazy components at module level |
| Static import elsewhere | Chunk never appears in the build | Remove or isolate the static import |
| Nested lazy components | Sequential requests, long wait | Preload or merge chunks |
| Splitting above-the-fold content | Slower LCP | Keep critical UI in the main bundle |
| Fallback flicker | Spinner flashes for a split second | Transitions, or a boundary higher up |
| Fallback with a different size | Layout shift | Reserve the space in the fallback |
| Stale chunk after deploy | "Failed to fetch dynamically imported module" | Retry or reload, plus an error boundary |
Pitfall: creating lazy components during render
lazy returns a new component type each time you call it. If you call it inside a component body, every render produces a different type. React then unmounts the old subtree and mounts a new one, which discards state and suspends again.
import { lazy, Suspense } from 'react';
// Wrong: a new component type on every render of Page
function Page() {
const Chart = lazy(() => import('./Chart'));
return (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
);
}The fix is to declare the lazy component once at module level:
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
export default function Page() {
return (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
);
}The same rule applies to any helper that wraps lazy. Call it at module scope, not in a render function or a hook.
Pitfall: a static import defeats the split
A bundler puts a module in a separate chunk only if every path to it goes through a dynamic import(). One static import anywhere in the main graph pulls the module into the main bundle. The lazy call still works, but it saves nothing.
// Header.jsx (part of the main bundle)
import { CHART_COLORS } from './Chart'; // static import of the heavy module
// Dashboard.jsx
import { lazy } from 'react';
const Chart = lazy(() => import('./Chart')); // no longer creates a separate chunkHere Chart.jsx and everything it imports ship with the first load because Header imports it. The usual fix is to move the shared constant into a small module that both files can import, such as chartColors.js.
Barrel files cause the same problem less obviously. If components/index.js re-exports every component, and the app imports from that index, a static import of one component can drag the heavy ones along. Import the heavy component directly from its own file, or confirm with the build report that the barrel does not pull it in.
Pitfall: request waterfalls
A waterfall is a chain of requests where each one can start only after the previous one finishes. Lazy components create waterfalls when one lazy component renders another. The browser downloads the parent chunk and runs it. Only then does React discover the child and request its chunk.
diagram mermaidMermaid source must be inside the diagram fence, so here is the real diagram:
Three remedies, in the order you should try them:
- Merge the chunks. If the child is always shown with the parent, import it statically from the parent. One chunk is faster than two sequential ones.
- Preload the child. Start the child's
import()when you start the parent's, for example in the same hover handler, as shown in the preloading chapter. - Split by route only. Route-level chunks are rarely nested, so they avoid most waterfalls.
Also be wary of a fetch waterfall hiding behind a code waterfall. A lazy component that fetches data in useEffect starts that request only after its chunk has loaded and rendered. Where you can, start the data request earlier, for example from the router or from a parent, and pass the promise down with use.
Pitfall: splitting the wrong things
Splitting is not free. Each chunk costs an HTTP request, some bundler runtime code, and a loading state to design. Split code that matches these conditions:
- It is large. A 2 KB component gains nothing from its own chunk.
- It is not needed for the first screen. Charts below the fold, modals, editors, admin pages and rarely used settings qualify.
- It is used by a minority of visits. If 95% of users open a feature, load it normally.
Do not lazy load the element that is likely to be the Largest Contentful Paint (LCP) element, such as a hero banner. Making it wait for an extra JavaScript download delays the metric you are trying to improve.
Pitfall: flicker and layout shift
Two fallback problems look like loading problems but are design problems.
Flicker happens when a chunk loads in 50 ms. The fallback appears and disappears so fast that it reads as a glitch. Options are to wrap navigation in a transition so the old screen stays visible, to move the boundary higher so a whole section shows one fallback, or to preload so the chunk is usually cached.
Layout shift happens when the fallback is much smaller or larger than the real content. When the chunk arrives, everything below jumps. This counts against Cumulative Layout Shift (CLS). Give the fallback the same dimensions as the content it stands in for:
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
function ChartSkeleton() {
return <div style={{ height: 320 }} aria-busy="true" />;
}
export default function Panel() {
return (
<Suspense fallback={<ChartSkeleton />}>
<Chart />
</Suspense>
);
}Pitfall: chunks that disappear after a deploy
Bundlers put a content hash in chunk file names, such as Settings-3f9a1c.js. When you deploy, the old files are often removed. A user who loaded the app before the deploy still runs the old main bundle, which references old chunk names. When that user opens Settings, the request returns a 404 or an HTML error page. The dynamic import rejects with an error such as "Failed to fetch dynamically imported module".
The error boundary from the earlier chapter keeps the page from crashing, but the user still sees a failure. A reload fixes it, because the new main bundle references the new names. You can do that automatically, once, with a wrapper:
import { lazy } from 'react';
export function lazyWithReload(load, key) {
return lazy(async () => {
const alreadyReloaded = sessionStorage.getItem(key) === '1';
try {
const module = await load();
sessionStorage.removeItem(key);
return module;
} catch (error) {
if (!alreadyReloaded) {
sessionStorage.setItem(key, '1');
window.location.reload();
// Stay suspended while the page reloads
return new Promise(() => {});
}
throw error;
}
});
}
// Usage, at module level
// const Settings = lazyWithReload(() => import('./Settings'), 'reload-settings');The sessionStorage flag prevents a reload loop when the failure is a real outage and not a stale chunk. On the second failure the error propagates to your error boundary.
Measuring the result
Never assume a split helped. Splitting can reduce the initial download and still make the experience worse through waterfalls or flicker. Measure three things: what is in the bundles, what the browser downloads, and how the page behaves for users.
1. Inspect the bundles
A bundle visualizer draws every chunk and the modules inside it. For Vite, add rollup-plugin-visualizer:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [
react(),
visualizer({ filename: 'stats.html', gzipSize: true }),
],
});Run vite build and open stats.html. Check that:
- the heavy library you meant to defer (a chart or editor library, for example) appears only in its own chunk;
- no large module appears in two chunks;
- the main chunk shrank by roughly the amount you expected.
With webpack, webpack-bundle-analyzer gives the same view. Compare gzip or Brotli sizes, since those are what travels over the network.
2. Watch the network under realistic conditions
Open DevTools, go to the Network panel, tick "Disable cache", and choose a throttling profile such as "Fast 4G" or "Slow 4G". Then reload and note:
- which JavaScript files load before first paint, and their total transferred size;
- whether chunk requests run in parallel or in a staircase, which indicates a waterfall;
- how long the fallback stays visible.
The Coverage tab (in the Command Menu, "Show Coverage") reports how much of each loaded script ran. A large main bundle with low coverage is a good candidate for further splitting.
3. Track user-facing metrics
Lighthouse gives a repeatable lab measurement. Field data from real users is more reliable, because their devices and networks differ from yours. The web-vitals package reports the main metrics:
import { onLCP, onINP, onCLS } from 'web-vitals';
function send(metric) {
navigator.sendBeacon('/analytics', JSON.stringify({
name: metric.name,
value: metric.value,
}));
}
onLCP(send);
onINP(send);
onCLS(send);Read the results as follows:
| Metric | What code splitting should do |
|---|---|
| LCP (Largest Contentful Paint) | Improve, or stay the same. A worse LCP means you split something critical. |
| INP (Interaction to Next Paint) | Improve slightly, since less script runs at startup. |
| CLS (Cumulative Layout Shift) | Stay the same. A worse CLS means a fallback has the wrong size. |
Record numbers before the change and after it, on the same throttling profile and with the cache disabled for the first-load case. Run each test several times, because single runs vary.
A short review checklist
- Every
lazycall is at module level. - The build report shows each lazy module in its own chunk, with no static imports elsewhere.
- No lazy component renders another lazy component on its first render, or the child is preloaded.
- The first screen, including the likely LCP element, is in the main bundle.
- Fallbacks match the final content's size, and navigation uses transitions where flicker appears.
- An error boundary sits outside Suspense, and stale chunks after a deploy are handled.
- Before and after numbers for bundle size, LCP and CLS confirm the improvement.
Exercise
A teammate wraps a modal in lazy and Suspense. After building, the visualizer shows that the modal's code is still in the main chunk. Name two likely causes and how you would confirm each.
Show answer
First, a static import of the modal file (or of a barrel file that re-exports it) exists somewhere in the main graph. Search for imports of that path, and check whether any index.js re-exports it. Second, a different module that is statically imported imports a value from the modal file, such as a constant. In the visualizer, look at which chunk contains the modal's module and which modules import it. Fix it by removing the static import or moving the shared value into a small separate module.
Exercise
Users report that right after each release, opening the Settings page shows an error for some people, but a manual reload fixes it. What is happening, and what two measures reduce the problem?
Show answer
Those users still run the old main bundle, which requests a Settings chunk file name that the deploy removed, so the dynamic import rejects. Measures: keep the previous release's chunk files on the server for a while after deploying, and handle the failure in code, for example with an error boundary that offers a retry plus a one-time automatic reload guarded by a sessionStorage flag to avoid reload loops.
Exercise
After splitting a dashboard, the bundle is 40% smaller but LCP got worse in Lighthouse. Give a likely cause and a way to check it.
Show answer
The element that determines LCP, such as a hero image or main heading section, now sits inside a lazy component, so it waits for an extra JavaScript download before rendering. Check the LCP element in the Lighthouse report or the Performance panel, and see whether it belongs to a lazy chunk. Move that component back into the main bundle, or preload its chunk, then compare LCP again under the same throttling.