Sub topic 12
Common pitfalls and measuring the result
This chapter assumes you know function components and hooks, ES module import and export, promises, and how to run a build with Vite or webpack. You have already seen React.lazy, Suspense, error boundaries, transitions, and preloading. Here you will learn the mistakes that cancel the benefit of code splitting, and how to check that a split helped.
Pitfalls that undo the gains
Declaring lazy components inside a component
lazy must be called at module level. If you call it inside a component body, every render creates a new component type. React sees a different type, throws away the old subtree, loads again, and shows the fallback each time.
import { lazy, Suspense } from 'react';
// Wrong: a new lazy component is created on every render.
function BadPanel() {
const Chart = lazy(() => import('./Chart'));
return (
<Suspense fallback={<p>Loading...</p>}>
<Chart />
</Suspense>
);
}
// Right: declared once, at module level.
const GoodChart = lazy(() => import('./Chart'));
function GoodPanel() {
return (
<Suspense fallback={<p>Loading...</p>}>
<GoodChart />
</Suspense>
);
}A named export without a mapping
lazy expects the module to have a default export. If Chart.jsx only has export function Chart(), the promise resolves to a module with no default, and React throws an error. Map the named export to default inside the import promise.
import { lazy } from 'react';
const Chart = lazy(() =>
import('./Chart').then((module) => ({ default: module.Chart }))
);Splitting too small
Every chunk costs an extra network request and some bundler overhead. Splitting a 2 KB component rarely pays off. Good candidates are large and not needed on first paint:
- Routes the user may never visit.
- Modals, drawers, and tabs that start closed.
- Heavy libraries such as charts, editors, and maps.
Splitting what is needed immediately
If a component appears in the first screen, lazy loading it adds a delay. The browser must load the main bundle, run it, discover the component, and only then request the chunk. This is a request waterfall. Keep above-the-fold content in the main bundle.
Missing or misplaced boundaries
A lazy component with no Suspense boundary above it throws an error. A boundary placed too high replaces the whole page with a fallback. Also remember that a failed chunk request rejects the import. Without an error boundary outside Suspense, that rejection crashes the tree.
Hiding the problem with fallbacks
A fallback that changes size causes layout shift. Reserve space with a skeleton of similar dimensions. Where the content is already visible, wrap the update in a transition so the old UI stays on screen.
Measuring the result
Do not assume a split helped. Measure it before and after.
- Build for production. Development builds are not representative.
- Inspect the bundle. Use a visualizer such as
rollup-plugin-visualizerfor Vite orwebpack-bundle-analyzerfor webpack. Confirm that the heavy library moved into its own chunk and is not also imported statically somewhere else. - Open the browser's Network panel with the cache disabled and throttling set to a slow connection. Check the size of the JavaScript loaded on first visit, and confirm the chunk loads only when you navigate to the feature.
- Run Lighthouse or the Performance panel. Compare Largest Contentful Paint (LCP), Total Blocking Time (TBT), and the amount of unused JavaScript.
A common cause of failed splits
One static import is enough to pull a module back into the main bundle. If App.jsx writes import { formatDate } from './Chart' while Chart is also lazy loaded, the bundler must keep Chart in the main chunk. The bundler analyzer shows this as the module appearing in the entry chunk. Move shared helpers into their own file so both sides can import them without dragging in the component.
// utils/formatDate.js holds the shared helper.
// App.jsx imports it directly.
import { lazy, Suspense } from 'react';
import { formatDate } from './utils/formatDate';
const Chart = lazy(() => import('./Chart'));
export default function App() {
return (
<main>
<p>{formatDate(new Date())}</p>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</main>
);
}Stale chunks after a deploy
Chunk file names usually contain a content hash. After a new deploy, old files may be removed. A user with the old page open then requests a chunk that no longer exists, and the import fails. Keep old assets available for a while after a deploy, and let your error boundary offer a reload button so the user can fetch the new build.
Checklist
| Check | What to look for |
|---|---|
| `lazy` placement | Declared at module level, not in a component |
| Exports | Default export, or mapped from a named export |
| Boundary | A Suspense boundary above every lazy component |
| Failure | An error boundary outside Suspense |
| Entry chunk | No static import of a lazy module |
| Layout | Fallback reserves space, no layout shift |
| Evidence | Before and after numbers from a production build |
Exercise
A teammate lazy loads a chart component, but the bundle analyzer still shows the chart library in the entry chunk. Name two likely causes and how you would confirm each.
Show answer
First, another file imports the chart module or the chart library statically, for example a helper exported from the chart file or a second component that imports the library at the top. Confirm by searching the code for static imports of that path and checking which module the analyzer lists as the importer. Second, the build used for analysis may be a development build, or the lazy call may sit inside a component so the split is not applied as expected. Confirm by running a production build and checking that lazy is declared at module level.
Exercise
Users report a blank page right after each deploy, and only when they were already on the site. What is the likely cause, and what two changes reduce the problem?
Show answer
Their open page references chunk files from the old build, which the deploy removed, so the dynamic import rejects and, with no error boundary, the tree crashes. Keep old assets available for some time after a deploy, and add an error boundary outside Suspense that shows a message with a reload button.