Sub topic 3
Loading components on demand with React.lazy
This chapter assumes you know function components and props, ES modules, promises, and have used a bundler such as Vite or webpack. Here you will move one component into its own chunk and load it only when it first renders.
What React.lazy does
React.lazy takes a function that returns a promise. That promise must resolve to a module whose default export is a React component. The usual way to write that function is a dynamic import(), which the bundler turns into a separate chunk.
React calls your function the first time the lazy component is rendered, not when it is declared. After the promise resolves, React caches the result and renders the real component. Later renders reuse it without another request.
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>
);
}Chart is not downloaded when Dashboard loads. The browser fetches the chunk when React first tries to render <Chart />. While the chunk downloads, the component suspends, and the nearest Suspense boundary above it shows the fallback. A lazy component must always render inside a Suspense boundary. Without one, React throws an error.
The lifecycle of a lazy component
During the Loading state the fallback is on screen. If the import rejects, for example because the network dropped, the error is thrown during render. Suspense does not catch it. An error boundary does, which a later chapter covers.
Default exports and named exports
React.lazy reads the default property of the loaded module. If your component uses a named export, lazy has nothing to render. 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 returns a new object shaped like a module. Alternatively, add export default Chart to the source file. Use the mapping when you cannot or do not want to change that file.
Common errors
- Calling
lazyinside a component. Each render creates a new lazy component type. React sees a different type every time, discards the loaded one, and the component reloads or loses its state. Declare lazy components at module level. - Missing
Suspense. React reports that a component suspended while rendering with no fallback boundary above it. Add a boundary above the lazy component. - Named export without mapping. The error mentions that the lazy element type is invalid, because
defaultisundefined. Use the.thenmapping shown above. - Splitting a tiny component. A chunk adds a network request. If the component is a few hundred bytes, the request costs more than the saving.
- Splitting something visible immediately. If the user sees the component on first paint, lazy loading only delays it. Split what is hidden at first: modals, tabs, rarely visited routes, heavy widgets.
Choosing what to lazy load
A good candidate is a component that is large, depends on a heavy library, and is not needed on first paint. A charting component that pulls in a large charting library is a typical case. When that component is lazy, the library moves into the chunk too, so users who never open the chart never download it.
Compare two candidates:
| Component | Size | Visible on first paint | Lazy load? |
|---|---|---|---|
| Header | Small | Yes | No |
| Chart with charting library | Large | No, behind a tab | Yes |
| Settings modal | Medium | No | Yes |
Exercise
A teammate writes const Panel = lazy(() => import('./Panel')) inside the body of Layout, and the panel reloads and loses its state on every render of Layout. What is wrong, and how do you fix it?
Show answer
Calling lazy inside a component creates a new component type on every render, so React treats Panel as a different component each time and cannot reuse the loaded one. Move the lazy call to module level, outside Layout.
Exercise
Chart.jsx contains export function Chart() { ... } and you write lazy(() => import('./Chart')). React fails to render it. Give two ways to fix this.
Show answer
Either add export default Chart to Chart.jsx, or map the named export in the import promise: lazy(() => import('./Chart').then((m) => ({ default: m.Chart }))).