Sub topic 3
Loading components on demand with React.lazy
This chapter assumes you know function components and props, useState, ES module import and export, and Promises. It also assumes you have seen a bundler such as Vite or webpack turn your code into files. The previous chapter covered dynamic import() and chunks. Here you use that tool from inside a React component tree.
What React.lazy does
React.lazy takes a function that returns a Promise for a module. It gives you back a component. Until that component first renders, React doesn't call your function, so the browser doesn't download the code.
import { lazy } from 'react';
const Chart = lazy(() => import('./Chart'));The call to lazy runs when the module containing it is evaluated. The import('./Chart') inside the arrow function runs later, on the first render of <Chart />. The bundler sees the import() call and puts Chart.jsx, and any code only it uses, into a separate file called a chunk.
lazy has no fallback UI of its own. A component made with lazy needs a Suspense boundary above it to show something while the chunk loads. If the boundary is missing, React throws an error. The next chapter covers boundaries in detail. This chapter uses the simplest form.
A first working example
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
export default function Dashboard() {
return (
<section>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</section>
);
}On the first render, the heading appears and the fallback text appears where the chart will go. When the chunk arrives, React replaces the fallback with the chart. The heading never disappears because it sits outside the boundary.
What happens on the first render
A lazy component keeps an internal record of its load state. It has four states: uninitialized, pending, resolved and rejected. React moves through them like this.
Three details follow from this model.
- Suspending means throwing. While the status is pending, the lazy component interrupts rendering. React catches this and renders the fallback of the nearest
Suspenseancestor. You never write this code yourself. - The result is cached. Once the Promise resolves, React stores the component. Later renders use it at once. If you unmount
<Chart />and mount it again, nothing is downloaded a second time. The browser and bundler also cache the module. - A rejection is cached too. If the Promise rejects, for example because the network dropped, every later render of that same lazy component throws the same error. Re-rendering doesn't retry the download. The chapter on error boundaries covers recovery.
The default export requirement
lazy expects the Promise to resolve to an object with a default property that holds a component. A module with export default already has that shape. A module with only named exports doesn't, and you get an error if you pass it directly.
Map the named export to default inside the Promise:
import { lazy } from 'react';
// Chart.jsx has a named export: export function Chart() { ... }
const Chart = lazy(() =>
import('./Chart').then((module) => ({ default: module.Chart }))
);The .then call changes the result after the module loads. Only the module you import is split out, so this costs nothing extra at runtime.
Call lazy at the top level of a module
Always define lazy components at module scope, next to your other imports. Don't define them inside a component.
import { lazy, Suspense } from 'react';
// Wrong: a new lazy component is created on every render
function Dashboard() {
const Chart = lazy(() => import('./Chart'));
return (
<Suspense fallback={<p>Loading...</p>}>
<Chart />
</Suspense>
);
}Each call to lazy returns a new component type with its own empty state. When Dashboard re-renders, React sees a different type from the last render. It throws away the old subtree, including any state inside it, and starts loading again. The result is a flash of fallback on every update and lost state.
Loading on a user action
A lazy component loads when it first renders, not when the page loads. This means you can tie a download to a user action by rendering the component only after the action.
import { lazy, Suspense, useState } from 'react';
const MarkdownEditor = lazy(() => import('./MarkdownEditor'));
export default function Note() {
const [editing, setEditing] = useState(false);
return (
<div>
<button onClick={() => setEditing(true)}>Edit</button>
{editing && (
<Suspense fallback={<p>Loading editor...</p>}>
<MarkdownEditor />
</Suspense>
)}
</div>
);
}Users who never click "Edit" never download the editor. This is the clearest case where lazy loading pays off. The cost is a short wait on the first click, which the preloading chapter shows how to reduce.
If you wrote <MarkdownEditor /> without the editing && check, the chunk would start loading as soon as Note renders. The code would be in a separate file, but the user would download it anyway.
Props, state and refs work normally
After the chunk loads, a lazy component behaves like any other component. You pass props to it as usual:
<Suspense fallback={<p>Loading chart...</p>}>
<Chart data={data} title="Weekly sales" />
</Suspense>State inside the loaded component works as usual. If the parent re-renders after the chunk has loaded, the lazy component updates in place without reloading. Props passed during loading are not lost. React renders the real component with the current props once it is ready.
What is worth splitting
Each chunk adds a network request and a moment of waiting. Splitting pays off when the saved bytes outweigh that cost.
Good candidates:
- Components that appear only after a user action, such as modals, editors and settings panels.
- Components that sit below the fold, such as charts or comment threads.
- Whole routes that most visitors don't open.
- Components that bring in large libraries, such as a charting, map or rich-text library.
Poor candidates:
- Content visible in the first screen. Splitting it delays the first paint, because the user waits for a second request before seeing it.
- Tiny components. The request overhead is larger than the code you save.
- Components that are always rendered together. Splitting them gives you several small requests where one would do.
Why the bundle may not shrink
Lazy loading only moves code into a separate chunk if nothing else pulls it into the main bundle. If any file in the main path imports the module statically, the bundler must include it in the main bundle.
import { lazy } from 'react';
import { formatLabel } from './Chart'; // static import of the same module
const Chart = lazy(() => import('./Chart'));Here ./Chart is loaded with the main bundle because of the first import, and the lazy call gains nothing. Move shared helpers into a separate file that both sides import. After a change like this, inspect the build output to confirm that a new chunk file exists. The last chapter shows how to measure this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error that a component suspended and no Suspense boundary exists | No `Suspense` ancestor above the lazy component | Wrap the lazy component, or a parent of it, in `Suspense` with a `fallback` |
| Error that the element type is invalid and got undefined, or that `default` is missing | The module has only named exports | Map the export with `.then((m) => ({ default: m.Name }))` |
| Fallback flashes on every parent update, and state resets | `lazy` is called inside a component | Move the `lazy` call to module scope |
| No separate chunk appears in the build | The module is also imported statically somewhere | Remove the static import or move shared code elsewhere |
| After a network failure, the component never loads again, even when the network returns | React caches the rejected Promise | Handle it with an error boundary that remounts a new load attempt |
| Wrong path or file name fails at build time or in the browser | Typo in the `import()` path | Check the path relative to the file that calls `import()` |
Summary of the working model
lazy(fn)returns a component.fnruns on the component's first render.fnmust return a Promise that resolves to{ default: Component }.- While the Promise is pending, the component suspends and the nearest
Suspenseboundary shows its fallback. - Declare lazy components at module level so their identity stays stable.
- A static import of the same module defeats the split.
Exercise
A teammate writes const Chart = lazy(() => import('./Chart')) at the top of a file, but Chart.jsx only has export function Chart() {...}. The page throws an error when the chart renders. What change fixes it, and why does the original fail?
Show answer
Change the factory to lazy(() => import('./Chart').then((m) => ({ default: m.Chart }))). lazy requires the Promise to resolve to an object with a default property holding the component. A module with only named exports has no default, so React gets undefined where it expects a component. The .then step builds an object with the right shape. The alternative is to add export default Chart to Chart.jsx.
Exercise
A component contains const Editor = lazy(() => import('./Editor')); inside its function body. Users report that typing in the editor sometimes resets it and the loading message flashes. Explain the cause and give the fix.
Show answer
Every render of the parent calls lazy again and creates a new component type. React treats it as a different component from the previous render, so it unmounts the old editor (losing its state), mounts a new one, and suspends again while it loads. Move the lazy call to module scope, above the component, so the same component type is used on every render.
Exercise
You lazy-load a settings panel, but the production build shows no separate chunk for it. Name one likely cause and how you would check for it.
Show answer
Another file in the main bundle probably imports the same module with a static import statement, so the bundler must include it in the main bundle. Search the project for other imports of the settings panel's path, and remove them or move the shared code into a separate module. Then rebuild and check that the output lists a separate chunk file for the panel.