Sub topic 14
Reducing load cost with code splitting
Earlier chapters in this tutorial dealt with render cost, the time React spends running components after the page is already running. This chapter deals with load cost, the time the browser spends downloading, parsing, and running JavaScript before the app becomes usable. The Profiler cannot see most of that work, so you use the browser's Network and Performance panels instead.
This chapter assumes you can read a basic Performance panel recording and that you know how import statements and function components work. You should also know that a production build is the only build whose numbers you can trust.
Why a large bundle is its own problem
A bundler (a tool such as Vite, webpack, or Rollup) combines your modules into files called bundles. By default, everything reachable from your entry file lands in one bundle. Every user then pays for every feature on the first visit, including the admin screen they will never open.
A large bundle costs time in three places:
- Download. Bytes cross the network. This hurts most on slow connections.
- Parse and compile. The browser turns the text into executable code. This hurts most on slow phones.
- Execution. Top-level module code runs before React renders anything.
Compression reduces only the download. Parsing and execution depend on the uncompressed size. A 300 KB gzipped bundle can be around 1 MB of JavaScript for the device to process.
Code splitting means dividing the bundle into several chunks and loading each chunk only when needed. The bundler does the splitting. Your code marks where the boundaries go, using dynamic import().
React.lazy and Suspense
React.lazy takes a function that returns a dynamic import(). It gives you a component that loads its module the first time React tries to render it. While the module loads, the nearest Suspense boundary above it shows its fallback.
import { lazy, Suspense } from "react";
const Chart = lazy(() => import("./Chart"));
export function Report() {
return (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
);
}Three rules apply here:
- The
lazy()call goes at module top level, not inside a component. If you call it during render, each render creates a new component type and React throws away the loaded state. - The imported module must have a default export that is a component.
- A
Suspenseboundary must exist above the lazy component. Without one, React reports an error.
Named exports
If the module exports the component by name, map it to default in the then callback:
import { lazy } from "react";
const Chart = lazy(() =>
import("./Chart").then((module) => ({ default: module.Chart }))
);Doing this inside a barrel file (an index.js that re-exports many modules) can pull the whole barrel into the chunk. Import from the specific file when you can.
Choosing where to split
Split points are worth the most where a large amount of code sits behind something the user has not done yet. Good candidates, in rough order of payoff:
| Split point | Why it works | Typical example |
|---|---|---|
| Route or screen | Users see one screen at a time | Settings, Reports, Admin |
| Heavy library behind an interaction | Library is large and used rarely | Rich text editor, PDF export, charting |
| Modal or drawer content | Hidden until opened | Export wizard |
| Locale or data files | Only one variant is needed | Translations |
Poor candidates are small components and anything visible on first paint. Splitting a 2 KB component adds a network request that costs more than the bytes saved. Splitting your above-the-fold content delays the first useful paint, which is the opposite of the goal.
Here is a screen-level split. It uses useTransition from the earlier chapter on deferring work, so the old screen stays visible while the new chunk loads instead of flashing a fallback.
import { lazy, Suspense, useState, useTransition } from "react";
const Reports = lazy(() => import("./Reports"));
const Settings = lazy(() => import("./Settings"));
export default function App() {
const [tab, setTab] = useState("reports");
const [isPending, startTransition] = useTransition();
function show(next) {
startTransition(() => setTab(next));
}
return (
<>
<nav style={{ opacity: isPending ? 0.6 : 1 }}>
<button onClick={() => show("reports")}>Reports</button>
<button onClick={() => show("settings")}>Settings</button>
</nav>
<Suspense fallback={<p>Loading...</p>}>
{tab === "reports" ? <Reports /> : <Settings />}
</Suspense>
</>
);
}The first render of this app still needs a fallback, because nothing is on screen yet. After that, switching tabs inside a transition keeps the current tab visible until the next one is ready.
Handling load failures
A chunk request can fail. The user may go offline, or you may have deployed a new version that deleted the old chunk file while their page was still open. A failed import makes the lazy component throw, and without an error boundary the whole tree unmounts.
Error boundaries must be class components. Wrap the Suspense boundary in one:
import { Component } from "react";
export class ChunkErrorBoundary extends Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
if (this.state.failed) {
return (
<p>
This section failed to load.{" "}
<button onClick={() => window.location.reload()}>Reload</button>
</p>
);
}
return this.props.children;
}
}Use it like this: <ChunkErrorBoundary><Suspense fallback={...}><Chart /></Suspense></ChunkErrorBoundary>. A reload fetches the new HTML, which points to the current chunk names.
Preloading to hide the delay
Lazy loading moves cost from startup to the moment of use. That moment can feel slow. If you can predict what the user will do next, start the download early. Keep the loader function in a variable, so you can call it both from lazy and from an event handler:
import { lazy, Suspense, useState } from "react";
const loadChart = () => import("./Chart");
const Chart = lazy(loadChart);
export function Report() {
const [open, setOpen] = useState(false);
return (
<>
<button
onMouseEnter={loadChart}
onFocus={loadChart}
onClick={() => setOpen(true)}
>
Show chart
</button>
{open && (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
)}
</>
);
}Calling import() more than once is safe. The module system caches the result, so repeated hover events do not trigger repeated downloads.
Measuring whether splitting helped
Splitting is an optimization, so the rule from the start of this tutorial applies: measure before and after, using a production build.
- Find what is in the bundle. Run a bundle analyzer, such as
rollup-plugin-visualizerfor Vite orwebpack-bundle-analyzerfor webpack. It shows a treemap of module sizes. Look for a single large dependency, or for libraries included twice. - Check the Network panel. Reload with the cache disabled and the throttling preset set to a slow network. Note the total JavaScript transferred before the page is usable, and confirm the lazy chunk is requested only when expected.
- Check the Performance panel. Record a page load with CPU throttling on. Look for long tasks (tasks over 50 ms) labelled with script evaluation and compilation. Compare the main-thread time before and after the change.
- Use the Coverage tool. In Chrome DevTools, the Coverage panel shows how much of each loaded file ran during your session. A file that is mostly unused is a splitting candidate.
Record the numbers in a table, as you did for render timings: JavaScript transferred, main-thread script time, and time until the page responds to input.
Gotchas
- Request waterfalls. If a lazy component, once loaded, renders another lazy component, the browser fetches them one after the other. Preload the inner one, or merge the two chunks.
- Too many small chunks. Each chunk is a request. Over HTTP/2 this is cheap, but dozens of tiny chunks still add latency and hurt compression.
- Layout shift. A fallback much smaller than the real content makes the page jump when the chunk arrives. Give the fallback roughly the same size.
- Shared code. If two lazy chunks use the same large library, most bundlers extract it into a shared chunk. Check the analyzer to confirm the library is not duplicated.
- Server rendering.
React.lazyworks with streaming server rendering in current React versions, but older setups needed a separate library. Check your framework's documentation. Frameworks such as Next.js also split by route automatically. - Development timings. Dev servers often serve modules individually and do not produce the chunks you will ship. Judge splitting results only from a production build.
Exercise
A page imports a 400 KB charting library at the top of Dashboard.jsx. The chart sits inside a modal that few users open. Describe how you would split it, what you would add to handle failure, and how you would confirm the change helped.
Show answer
Replace the static import of the chart component with const Chart = lazy(() => import("./Chart")) at module top level, and render it inside <Suspense fallback={...}> only when the modal opens. Wrap the Suspense boundary in an error boundary so a failed chunk request shows a reload option instead of unmounting the tree. Optionally call the loader function on button hover or focus to preload. To confirm the result, build for production and compare before and after. Check the analyzer to see the library moved into its own chunk, check the Network panel to see that chunk is requested only when the modal opens, and compare transferred JavaScript and main-thread script time on initial load in the Performance panel with CPU throttling.