Sub topic 1
Why split code: bundles and load cost
Prerequisites
This chapter assumes you already know the following:
- Function components and props in React.
- Hooks basics:
useStateanduseEffect. - ES modules:
importandexport. - What a bundler such as Vite or webpack does at a high level.
- Promises and basic async JavaScript.
You do not need to know React.lazy or Suspense yet. This chapter explains the problem they solve. Later chapters cover the tools.
What a bundle is
Your source code is spread across many files. A bundler follows the import statements from an entry file, collects every module it reaches, and writes them into one or more output files. Those output files are called bundles. The browser downloads the bundles, parses them, and runs them.
By default, most setups produce one large bundle for the whole application. Every component, every library, and every page ends up in that file. A user who only visits the home page still downloads the code for the settings page, the admin tools, and the chart library.
Why bundle size costs time
Downloading is only the first cost. JavaScript is more expensive than an image of the same size, because the browser has to do several things with it.
- Download. The bytes cross the network. This depends on bandwidth and latency.
- Decompress. Servers usually send gzip or Brotli. The browser expands the file.
- Parse and compile. The engine reads the text and turns it into executable form.
- Execute. Top-level code in each module runs, and React renders and hydrates the first screen.
An image of 200 KB takes time to download and decode, but it does not block the page from responding to clicks. A 200 KB script (compressed size) can expand to several times that size once decompressed. It then occupies the browser's main thread while it is parsed and run. During that time the page may look ready but ignore taps and clicks.
Two common metrics capture this cost:
| Metric | What it measures | How bundle size affects it |
|---|---|---|
| Largest Contentful Paint (LCP) | When the largest visible element finishes rendering | A big bundle delays the render that produces the element |
| Interaction to Next Paint (INP) | How quickly the page responds to input | Long script tasks on the main thread block input handling |
| Total Blocking Time (TBT) | Lab measure of main-thread time blocked by long tasks | Parsing and executing large scripts creates long tasks |
Slow devices and networks amplify the effect. A phone with a slower CPU can take several times longer than a developer laptop to parse the same file. If you test only on a fast machine with a local server, you will underestimate the cost.
The idea of code splitting
Code splitting means dividing the bundle into several smaller files, called chunks, and loading each chunk only when it is needed. The browser downloads a small initial chunk to render the first screen. Other chunks arrive later, when the user navigates or opens a feature that needs them.
The total amount of code does not shrink. What changes is the timing. Code that the first screen does not need leaves the critical path.
Where the savings come from
Not every piece of code is worth splitting. The best candidates share two traits: they are large, and they are not needed for the first render.
- Routes. A user sees one page at a time. Code for other pages can wait. This is usually the biggest and safest win.
- Heavy widgets. Charts, rich text editors, maps, code editors, and PDF viewers often bring in large libraries.
- Content behind interaction. Modals, drawers, tabs that are not selected, and "advanced" panels appear only after a click.
- Rarely used features. Admin screens, export tools, and onboarding flows reach a small share of users.
- Large third-party libraries used in one place. A date library or a markdown parser that only one screen uses should not weigh down every page.
Poor candidates are code that every user needs immediately, such as the app shell, the navigation bar, and the components on the landing screen. Splitting these only adds network requests and delays the first paint.
A worked example
Suppose a dashboard app has this structure and these approximate sizes after minification and compression:
| Module | Size (gzip) | Needed on first screen? |
|---|---|---|
| React and React DOM | 45 KB | Yes |
| App shell and home page | 30 KB | Yes |
| Charting library | 120 KB | No, only on the reports page |
| Settings page | 25 KB | No |
| Markdown editor | 90 KB | No, only when a user writes a note |
With a single bundle, the user downloads 310 KB before seeing anything. With splitting, the initial load is 75 KB (React plus the shell and home page). The other 235 KB is divided into three chunks that load on demand.
These numbers are illustrative. Your own figures will differ, and you should measure them with a bundle analyzer, which a later section describes.
Here is the kind of code that causes the problem. The dashboard imports a heavy chart component at the top of the file, so the bundler must include it in the same bundle as the dashboard:
import { useState } from 'react';
import Chart from './Chart'; // pulls in a large charting library
export default function Dashboard() {
const [showChart, setShowChart] = useState(false);
return (
<section>
<h1>Dashboard</h1>
<button onClick={() => setShowChart(true)}>Show chart</button>
{showChart && <Chart />}
</section>
);
}The chart does not render until the user clicks the button. Even so, the static import at the top forces the bundler to include Chart and its library in the initial bundle. A static import is resolved at build time and is always part of the module graph that the entry file reaches.
The next chapters show how to replace this static import with a dynamic one, so the chart code downloads only when it is needed.
Trade-offs of splitting
Code splitting is not free. It trades a smaller initial download for extra work later.
- More requests. Each chunk is a separate network request. With HTTP/2 and HTTP/3 the per-request overhead is small, but a request still has latency.
- Delay at the moment of need. When the user clicks, the chunk may not be there yet. Without care, they see a spinner or a blank area.
- Loading states to design. Every split point needs a plan for what the user sees while the chunk loads.
- Failure modes. A chunk request can fail. The user may be offline, or a new deployment may have removed the old file. You need to handle this.
- Less effective compression. Many small files compress slightly worse than one large file, and shared code can be duplicated unless the bundler extracts it into a shared chunk.
Splitting makes sense when the saving on the first load is larger than the cost of waiting later. The later chapters of this tutorial give you tools to reduce that waiting cost: fallbacks, transitions, and preloading.
How bundlers decide chunk boundaries
Bundlers create chunks from the module graph. A few rules apply in practice:
- The entry file and everything it reaches through static
importstatements go into the initial chunk. - A dynamic
import()call marks a split point. The module it names, and the modules only that module reaches, go into a new chunk. - When two chunks both import the same module, the bundler can move it into a shared chunk so it is not downloaded twice. Vite (through Rollup) and webpack both do this, with different default heuristics.
- Chunk file names usually include a content hash, such as
Chart-3f9a1c.js. When the file's content changes, the name changes, so browsers can cache old files for a long time without serving stale code.
The consequence of rule 1 is important. One static import anywhere in the initial graph pulls the module into the initial chunk, even if you also use a dynamic import for it elsewhere. If a heavy module is imported statically in a utility file that the entry reaches, splitting it in a component file achieves nothing.
// utils/format.js
import { renderChart } from './chartLib'; // static import in the initial graph
export function formatReport(data) {
return renderChart(data);
}If Dashboard lazily loads Chart, but utils/format.js is imported by the app shell, chartLib still lands in the initial bundle. A bundle analyzer shows this clearly, because the library appears in the initial chunk.
Measuring before you split
Do not split by guesswork. Measure first.
- Bundle analyzers draw your bundles as a treemap, with each module sized by its weight. For webpack, use
webpack-bundle-analyzer. For Vite, userollup-plugin-visualizer. - Browser DevTools. The Network panel shows each request's size and timing. The Coverage panel shows how much of each loaded script ran during a page load. A large share of unused code in the initial bundle suggests splitting candidates.
- Lighthouse and Web Vitals report LCP, TBT, and INP. Compare before and after a change, on a throttled connection and CPU.
A minimal Vite setup for the visualizer looks like this:
// 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 }),
],
});After npm run build, open stats.html in a browser. Look for large modules inside the initial chunk that the first screen does not use. Those are your candidates.
What this means for React
React itself offers no built-in way to split a bundle. Splitting is done by the bundler, triggered by a dynamic import(). What React adds is a way to use the result inside a component tree. React.lazy turns a dynamic import into a component, and Suspense defines what to show while it loads. The following chapters build on this:
- The dynamic
import()expression and what a chunk is at run time. React.lazy, which wraps an import as a component.Suspense, which shows a fallback during loading.- Where to place boundaries, how to split by route, and how to handle failures.
Keep the goal from this chapter in mind throughout. Every technique that follows either moves code off the critical path or hides the cost of loading it.
Exercise
An app has one 400 KB (gzip) bundle. A 150 KB charting library is imported at the top of Reports.jsx, which the router renders only on /reports. The home page is the usual entry point. Name two reasons why this library is a good candidate for splitting, and one situation where splitting it would not reduce the initial bundle.
Show answer
It is large (150 KB, over a third of the bundle) and it is not needed for the first screen, since only the /reports route uses it. Moving it into its own chunk takes it off the critical path for users who land on the home page. Splitting would not help if another module in the initial graph, such as a shared utility imported by the app shell, also imports the charting library statically. The bundler would keep the library in the initial chunk.
Exercise
A teammate splits every component in the app into its own lazy chunk, including the navigation bar and the landing page hero. Initial bundle size drops, but the first paint gets slower. Why might this happen?
Show answer
The navigation bar and hero are needed for the first render, so the browser must now request their chunks before it can show anything. The entry chunk loads, learns it needs more chunks, and then fetches them. This creates a request waterfall and extra latency. Only code that is not needed for the first screen should be split off.