Sub topic 4
Showing a fallback with Suspense
The previous chapter showed how React.lazy turns a dynamic import() into a component that loads on demand. This chapter covers the other half of that pairing. Suspense decides what the user sees while the code is still downloading.
This chapter assumes you can write function components with props, use useState, and read import and export syntax. It also assumes you know that a Promise is an object that settles later with a value or an error.
What a Suspense boundary does
Suspense is a component that wraps part of your tree. It takes a fallback prop, which is any React node. If something inside the boundary is not ready to render, React shows the fallback in place of the whole boundary content. When the thing becomes ready, React swaps the real content in.
The basic form looks like this:
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. The chart area shows "Loading chart..." until the Chart chunk arrives.
How suspending works
A component is "suspended" when React tries to render it and it cannot produce output yet. A lazy component suspends on first render because its code has not loaded. You can trace the sequence like this:
- React starts rendering
Dashboardand reaches<Chart />. lazycalls your loader function, which callsimport('./Chart')and returns a promise. React remembers that promise.- The lazy component signals that it cannot render yet. React walks up the tree to find the nearest
Suspenseboundary above it. - React renders that boundary's
fallbackinstead of its children. - When the promise resolves, React retries rendering the children. This time
Charthas code, so it renders normally and replaces the fallback.
Two details follow from this model:
- The suspended component does not mount. It has no state, no effects, and no DOM nodes until the retry succeeds.
- The fallback replaces the entire boundary content, not just the suspended child. Siblings inside the same boundary are hidden too.
One boundary, several children
Because the boundary swaps all of its content, several lazy children inside one boundary appear together:
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
const Table = lazy(() => import('./Table'));
export default function Report() {
return (
<Suspense fallback={<p>Loading report...</p>}>
<Chart />
<Table />
</Suspense>
);
}React shows one fallback until both Chart and Table are ready. If Chart arrives first, the user still sees the fallback until Table arrives. This avoids a half-built layout, but it also means the slowest child sets the wait. Splitting this into two boundaries gives independent loading. That choice is the subject of the next chapter, so the tradeoff is only noted here.
Trying it with a visible delay
On a fast local server the chunk loads in a few milliseconds and you may never see the fallback. To observe it, add an artificial delay in the loader. Use this only in a demo.
import { lazy, Suspense, useState } from 'react';
const Chart = lazy(() =>
new Promise((resolve) => setTimeout(resolve, 1500)).then(() =>
import('./Chart')
)
);
export default function Demo() {
const [show, setShow] = useState(false);
return (
<section>
<button onClick={() => setShow(true)}>Show chart</button>
{show && (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
)}
</section>
);
}This assumes Chart.jsx has a default export, for example:
export default function Chart() {
return <p>Chart is ready.</p>;
}Click the button and the paragraph "Loading chart..." appears for about 1.5 seconds. Click again after it loads and nothing is delayed, because the module is already in the bundler's cache and the lazy component remembers its result.
What Suspense reacts to
Suspense only responds to components that suspend. A component suspends when it uses a source that is built to signal this to React. The common sources are:
React.lazycomponents whose code has not loaded.- The
usehook reading a pending promise (covered in a later chapter). - Data libraries and frameworks that integrate with Suspense.
Suspense does not detect a plain fetch inside useEffect. Such a component renders immediately with empty state, so there is nothing to suspend and the fallback never appears. If you wrap an effect-based loader in Suspense and see no fallback, this is why.
Boundary lookup rules
Where the fallback appears depends on where boundaries are in the tree. These rules cover most cases:
| Situation | Result |
|---|---|
| One boundary above the suspended component | That boundary's fallback shows |
| Several boundaries above it | The nearest (innermost) one shows its fallback |
| No boundary above it | React reports an error instead of rendering |
| The fallback itself suspends | React looks for the next boundary above the first one |
The last row matters if you try to make a fallback a lazy component. A fallback that suspends cannot be shown by its own boundary, so the loading state moves up the tree or fails. Keep fallbacks small, synchronous, and part of your main bundle.
The "no boundary" case is common during migration. If you add React.lazy to a component and the page now throws a message about a component suspending without a fallback, add a Suspense boundary above it.
Hiding and restoring content
The first suspension of a boundary replaces nothing visible, because nothing was shown yet. A second case is different. A boundary can already show content and then have a child suspend again, for example when a state change renders a different lazy component inside it.
In that case, unless the update is a transition, React hides the existing content and shows the fallback. In React 18 and later, the hidden content stays mounted. Its component state is preserved, and the browser keeps the DOM nodes with display: none applied. Layout effects inside the hidden content are cleaned up and run again when the content is shown again.
This is why switching tabs inside a boundary can make a form lose focus or flash a spinner even though state is intact. Transitions, covered in a later chapter, avoid the replacement by keeping the old content on screen while the new content loads.
Designing the fallback
The fallback is part of your interface and deserves some care.
- Match the size of the final content. If a 400 pixel tall chart is replaced by a one-line "Loading...", the page jumps when the chart appears. Reserve space with a fixed height or a skeleton that has the same shape.
- Keep it cheap. A fallback with images, animations, or large dependencies defeats the point of splitting.
- Make it meaningful. "Loading chart..." tells the user what is coming. A bare spinner in a corner of the screen tells them less.
- Consider showing nothing.
fallback={null}is valid. For a small, non-critical widget, blank space may be better than flashing a spinner for 50 milliseconds. - Make it accessible. Wrap text in an element such as
<p role="status">so screen readers announce the change.
function ChartSkeleton() {
return (
<div
role="status"
aria-label="Loading chart"
style={{ height: 400, background: '#eee' }}
/>
);
}
// <Suspense fallback={<ChartSkeleton />}>
// <Chart />
// </Suspense>React does not delay the fallback for you. If the chunk loads in 30 milliseconds the fallback may flash for a frame or two. That flash is often worse than a short blank, so test on a throttled connection and on a fast one before deciding.
Common errors
Defining lazy inside a component. This is the most frequent mistake. Each render creates a new lazy component type, so React treats it as a different component, discards the old one, and suspends again.
// 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>
);
}
// Right: define it once at module level
const Chart = lazy(() => import('./Chart'));
function Dashboard() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Chart />
</Suspense>
);
}The symptom is a fallback that appears again on every re-render, and any state inside Chart resets.
Expecting Suspense to catch errors. If the import fails, the promise rejects. Suspense has no way to handle that and the error propagates upward, which can unmount your whole app. Pair boundaries with an error boundary, as the chapter on load failures explains.
Wrapping Suspense around nothing that suspends. It is harmless but misleading. Readers of the code will assume something below it loads lazily.
Placing the boundary too low. A boundary must be above the lazy component, not inside it. A Suspense written inside the lazy component's own file cannot catch that component's own loading.
Summary of the working model
Suspenseshowsfallbackwhile any descendant is not ready, and swaps in the real content when all descendants are ready.- The nearest boundary above the suspended component is used.
- Suspended components do not mount, and the fallback replaces the whole boundary content.
- Only suspending sources trigger it. Effect-based fetching does not.
- Define
lazycomponents at module level, and design fallbacks to match the final layout.
Exercise
A component wraps <Settings /> in <Suspense fallback={<p>Loading...</p>}>, where Settings is created with lazy at module level. Inside Settings, a useEffect calls fetch to load user data and stores it in state. A developer expects "Loading..." to show until the data arrives, but the fallback only appears while the chunk downloads. Why, and what must change for Suspense to cover the data wait?
Show answer
Suspense only reacts to components that suspend, and a lazy component suspends only while its code loads. A useEffect fetch runs after the component has already rendered with empty state, so nothing suspends during the data wait. To have Suspense cover the data, read it with a Suspense-compatible source such as the use hook on a promise, or a data library that supports Suspense. Otherwise, keep the effect and track a loading flag in component state.
Exercise
A page has <Suspense fallback={<p>Loading...</p>}><Chart /><Table /></Suspense>, both lazy. Chart loads in 100 ms and Table in 900 ms. What does the user see at 500 ms, and why?
Show answer
The user sees "Loading...". One boundary swaps all of its content at once, so React keeps the fallback until every suspended child inside it is ready. Chart stays hidden until Table arrives at about 900 ms.
Exercise
Why does defining const Chart = lazy(() => import('./Chart')) inside the Dashboard function cause the fallback to reappear on every render?
Show answer
Each render of Dashboard creates a new lazy component, which is a new component type. React sees a different type than last time, unmounts the old one, and mounts the new one, which suspends again. Moving the lazy call to module level creates it once.