Sub topic 9
Transitions, deferred values and Suspense
This chapter assumes you know React function components, useState, props, and how a re-render walks the component tree. You should know what React.memo does. A basic idea of Suspense helps: a component can "suspend" while it waits for data or code, and a <Suspense> boundary above it shows a fallback until it is ready.
Earlier chapters covered how useTransition and useDeferredValue mark work as non-urgent. This chapter covers what happens when that non-urgent work suspends. The result is that content already on screen stays visible instead of being replaced by a spinner.
The problem: Suspense hides what the user already sees
A Suspense boundary has one job. When something inside it suspends, React replaces the boundary's content with the fallback. That is fine on first load, because there is nothing to show yet. It is a poor experience on a later update. Suppose the user clicks a tab and the new tab's content needs data. If the update is urgent, React hides the whole tab area behind a spinner. The user loses the content they were looking at and sees a loading state that flashes for a moment.
A transition changes this rule. If an update inside a transition suspends, React does not show the fallback for boundaries that are already revealed. It keeps the old UI on screen, renders the new UI in the background, and commits it once it is ready.
The diagram contains a second rule worth noting. A transition only protects boundaries that are already visible. If the update causes a new boundary to appear for the first time, React still shows that boundary's fallback.
Transitions with Suspense
Here is a complete example. It uses use from React 19 to read a promise, and a small cache so the same promise is reused for the same artist. Without a cache, each render would create a new promise and suspend forever.
import { Suspense, useState, useTransition, use } from 'react';
const cache = new Map();
function fetchAlbums(artist) {
if (!cache.has(artist)) {
cache.set(
artist,
new Promise((resolve) => {
setTimeout(() => resolve([`${artist}: Album 1`, `${artist}: Album 2`]), 1000);
})
);
}
return cache.get(artist);
}
function Albums({ artist }) {
const albums = use(fetchAlbums(artist));
return (
<ul>
{albums.map((a) => (
<li key={a}>{a}</li>
))}
</ul>
);
}
export default function App() {
const [artist, setArtist] = useState('Ada');
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => {
setArtist(next);
});
}
return (
<>
<button onClick={() => select('Ada')}>Ada</button>
<button onClick={() => select('Grace')}>Grace</button>
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<Suspense fallback={<p>Loading...</p>}>
<Albums artist={artist} />
</Suspense>
</div>
</>
);
}On the first render, Albums suspends and the fallback shows, because nothing is visible yet. After the albums for Ada appear, click "Grace". The setArtist call is inside startTransition, so React keeps showing Ada's list. isPending becomes true and the list dims. After one second the Grace list replaces it. The "Loading..." text never reappears.
If you remove startTransition and call setArtist(next) directly, the same click replaces the list with "Loading..." for a second.
Deferred values with Suspense
useDeferredValue gives the same protection without you wrapping a setState call. This helps when you do not own the code that sets the value, for example when it arrives as a prop.
import { Suspense, useState, useDeferredValue, use } from 'react';
const cache = new Map();
function search(query) {
if (!cache.has(query)) {
cache.set(
query,
new Promise((resolve) => {
setTimeout(() => resolve([`${query} result 1`, `${query} result 2`]), 800);
})
);
}
return cache.get(query);
}
function Results({ query }) {
if (query === '') return <p>Type to search.</p>;
const results = use(search(query));
return (
<ul>
{results.map((r) => (
<li key={r}>{r}</li>
))}
</ul>
);
}
export default function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<Suspense fallback={<p>Loading...</p>}>
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<Results query={deferredQuery} />
</div>
</Suspense>
</>
);
}When the user types "a" after seeing results for an earlier query, query updates at once, so the input stays responsive. React first tries to re-render with the old deferredQuery. Then it tries a background render with the new value. That background render suspends, so React discards it for now and keeps showing the old results. When the data arrives, the background render completes and the new results appear. The fallback does not flash.
How the two differ in what they defer
The two tools produce a similar visual result, but they work at different points.
| Aspect | `useTransition` / `startTransition` | `useDeferredValue` |
|---|---|---|
| What you wrap | The state update call | A value you read during render |
| Where the old content comes from | The old state, since the update has not committed | The old value, returned by the hook |
| Pending signal | `isPending` | Compare the value to its deferred copy |
| Requires access to the setter | Yes | No |
With a transition, the state itself stays at the old value until the transition commits. With a deferred value, the state updates immediately and only one derived read lags behind. Both rely on React being able to render two versions of the tree and throw one away.
What counts as "already visible"
The rule that decides whether the fallback appears is about boundaries that have already been revealed. A few cases show how it plays out.
- A boundary that has content on screen and re-suspends inside a transition keeps its old content.
- A boundary that is rendering for the first time shows its fallback, even inside a transition.
- A boundary that is mounted fresh because its
keychanged is treated as new. React shows its fallback. - A boundary that is rendered inside a component that was just added to the tree is also new.
The key case catches many people. If you reset a component by changing key to force a remount, the Suspense boundary inside it starts over. The transition cannot hold back a fallback for a boundary that no longer exists.
// The key changes on every selection, so the whole subtree remounts.
// Inside a transition, the fallback will still appear.
<Suspense fallback={<p>Loading...</p>} key={artist}>
<Albums artist={artist} />
</Suspense>Put the key on something outside the boundary only if you want that reset. If you want the old content kept during loading, do not change the key of the boundary.
Nested boundaries and fallbacks you want to keep
Sometimes you do want a fallback for part of the page during a transition. A common case is a layout with a stable shell and a slow inner panel. You can place a nested boundary around the panel and give it a key, so that the panel shows its own fallback while the shell stays.
<Suspense fallback={<PageSkeleton />}>
<Layout>
<Suspense fallback={<PanelSkeleton />} key={id}>
<Panel id={id} />
</Suspense>
</Layout>
</Suspense>Here, a transition that changes id keeps the layout and shows PanelSkeleton only in the panel, because the keyed inner boundary is new each time. The outer boundary never shows PageSkeleton again, because it stays revealed. You choose where the loading state appears by choosing where boundaries and keys go.
Common errors with Suspense and concurrent updates
- Creating a new promise on every render. If
use(fetch(...))runs inside the component with no cache, each retry creates a new promise, and the component never finishes. Cache promises outside render, or use a library or framework that does it for you. - Expecting a transition to protect a first load. Nothing is on screen yet, so React must show the fallback.
- Changing the boundary's
keyand expecting old content to stay. A new key means a new boundary. - Updating state after an
awaitwithout a transition. In an async transition, updates made after anawaitlose their transition status unless you wrap them in anotherstartTransition. - Using
isPendingwith a deferred value.useDeferredValuedoes not return a pending flag. Compare the original and deferred values yourself. - Forgetting
memoon a child that receives a deferred value. Withoutmemo, the child re-renders for the urgent update too, and the benefit of deferring is lost. This matters most for slow children that do not suspend.
Choosing between them for Suspense work
- Use
startTransitionwhen you control the event handler and the update is a navigation or a selection, such as a tab or a route change. - Use
useDeferredValuewhen a value comes from props, from a library, or from an input where you want the input itself to stay urgent. - Use neither when you want a fallback to show. Update the state urgently and let the boundary display its fallback.
Exercise
A page shows a list of orders inside a <Suspense> boundary. Clicking a status filter calls setStatus(next) directly, and the list is replaced by a spinner each time. Describe two changes that keep the old list visible while the new list loads, and say one thing that would still cause the spinner to appear.
Show answer
First change: wrap the update in a transition with startTransition(() => setStatus(next)) from useTransition, and optionally dim the list using isPending. Second change: pass the status to the list component through useDeferredValue(status) and use the deferred value for the data read, so the old list stays until the new one is ready. The spinner would still appear on the very first load, because no content is visible yet. It would also appear if the boundary's key changes with the filter, because that creates a new boundary.
Exercise
A component does const data = use(fetch('/api/items').then((r) => r.json())) inside its body and is used inside a transition. The page never finishes loading. Why, and how do you fix it?
Show answer
Each render creates a new promise, so React suspends, retries, and creates another new promise, which never resolves in time for the render. Create the promise outside the render path and reuse it, for example by storing it in a cache keyed by the request, or by using a data library or framework that caches for you.