Sub topic 4
Showing a fallback with Suspense
This chapter assumes you know function components and props, useState and useEffect, ES module import and export, and basic promises. You should also have seen React.lazy and dynamic import(), covered in the previous chapters.
What Suspense does
React.lazy gives you a component whose code is not downloaded until it first renders. While the download is in progress, React has nothing to show for that component. Suspense fills that gap. It is a built-in component that displays a fallback while anything inside it is not ready.
The working model has three parts:
- A child component "suspends" when it tries to render but its code (or data) is not available yet.
- React stops rendering that subtree and looks upward for the nearest
Suspenseboundary. - React renders that boundary's
fallbackinstead. When the code arrives, React retries the render and swaps in the real content.
A first 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>
);
}The heading renders immediately because it sits outside the boundary. Only the area inside Suspense is replaced by the fallback. Once ./Chart has loaded, the paragraph disappears and Chart takes its place.
What the fallback can be
The fallback prop accepts any React node. A plain string works, but a good fallback reduces visual jumping:
- A skeleton that matches the size and layout of the final content avoids layout shift.
- A small spinner suits compact areas such as a button or a panel.
nullis valid when the content is not important and a flash of text would be worse than a brief gap.
Keep the fallback itself cheap. It should be plain markup, not a component that loads its own code. A fallback that suspends would need a boundary above it.
Rules that surprise people
- A lazy component must be inside a Suspense boundary. Without one, React throws an error when the component suspends. In a client-only app, one boundary near the root is the minimum.
- The nearest boundary wins. If boundaries are nested, only the closest one above the suspending component shows its fallback. Outer content stays visible.
- One boundary covers many children. If several lazy components sit in the same boundary, the fallback shows until all of them are ready. This groups loading states, which is sometimes what you want and sometimes not.
- State inside the boundary is not lost on the first load. The suspended subtree never mounted, so there is nothing to lose. But if a boundary that already shows content suspends again, React hides the existing content and shows the fallback.
- Define lazy components at module level. Calling
lazyinside a component creates a new component type on every render, which resets its state and triggers a fresh load.
import { lazy, Suspense } from 'react';
// Wrong: a new lazy component is created on every render
function Bad() {
const Chart = lazy(() => import('./Chart'));
return (
<Suspense fallback={<p>Loading...</p>}>
<Chart />
</Suspense>
);
}
// Right: created once, when the module loads
const GoodChart = lazy(() => import('./Chart'));
function Good() {
return (
<Suspense fallback={<p>Loading...</p>}>
<GoodChart />
</Suspense>
);
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error: a component suspended while responding to synchronous input | The suspending update was not inside a transition, and no boundary handles it | Add a `Suspense` boundary, or wrap the update in `startTransition` |
| Fallback flashes for a split second on every visit | The chunk is small or cached, so the fallback shows only briefly | Use a layout-matched skeleton, or a transition (see the transitions chapter) |
| Nothing renders and the console shows "Element type is invalid" | The module has no default export | Map a named export to `default` in the import promise |
| Page goes blank after a deploy | The chunk request failed | Add an error boundary outside `Suspense` (covered in a later chapter) |
Fallback is for loading, not for failure
Suspense only handles the waiting state. If the dynamic import rejects, for example because the network dropped, the boundary does not show the fallback forever. The error propagates up to the nearest error boundary. Without one, the whole tree unmounts. Planning for that case is the subject of a later chapter.
Exercise
A page has a Suspense boundary at the root with the fallback "Loading app...". Inside the page, a sidebar and a chart are both lazy, with no other boundaries. The sidebar chunk arrives first and the chart chunk arrives two seconds later. What does the user see during those two seconds, and how would you change the code so the sidebar appears as soon as it is ready?
Show answer
The user sees only "Loading app...", because one boundary covers both components and its fallback stays until both are ready. To show the sidebar early, wrap the sidebar and the chart each in their own Suspense boundary with their own fallbacks. Then each area replaces its fallback independently.