Sub topic 14
Suspense and the use hook
So far the component has asked for data inside an effect and tracked isLoading and error by hand. Suspense and the use hook move that bookkeeping out of the component. The component reads a promise as if the value were already there. React pauses rendering until the promise settles. This chapter assumes you know promises, error boundaries at a basic level, and the hooks from the earlier chapters. The use hook needs React 19 or later.
What Suspense does
Suspense is a component that shows a fallback while something inside it is not ready to render. You wrap part of the tree in a boundary:
<Suspense fallback={<p>Loading...</p>}>
<UserProfile userId={1} />
</Suspense>If UserProfile suspends, React discards that render attempt. It shows the fallback in place of everything inside the nearest boundary. When the thing it waited for is ready, React renders the children again.
Suspense does not watch your network requests. A fetch inside useEffect never triggers it, because the component has already rendered by the time the effect runs. Only a few sources can suspend a component:
use(promise), covered below.lazycomponents, which load code on demand.- Libraries and frameworks that integrate with Suspense, such as TanStack Query's
useSuspenseQueryand Server Components frameworks.
Reading a promise with use
use takes a promise and returns its resolved value. While the promise is pending, the component suspends. If the promise rejects, React throws the error to the nearest error boundary.
import { Suspense, use, useState, useTransition } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
const userPromises = new Map();
function getUser(userId) {
if (!userPromises.has(userId)) {
const promise = fetch(`/api/users/${userId}`).then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
});
userPromises.set(userId, promise);
}
return userPromises.get(userId);
}
function UserProfile({ userId }) {
const user = use(getUser(userId));
return <h1>{user.name}</h1>;
}
export default function App() {
const [userId, setUserId] = useState(1);
const [isPending, startTransition] = useTransition();
return (
<>
<button
onClick={() => startTransition(() => setUserId((id) => id + 1))}
disabled={isPending}
>
Next user
</button>
<ErrorBoundary fallback={<p>Could not load the user.</p>}>
<Suspense fallback={<p>Loading...</p>}>
<UserProfile userId={userId} />
</Suspense>
</ErrorBoundary>
</>
);
}UserProfile has no useState, no useEffect, and no isLoading flag. Compare it with the first component in this tutorial. The three request states now live in three places:
- Loading is the
Suspensefallback. - Error is the error boundary.
react-error-boundaryis a small library that provides one. You can also write your own class component. - Success is the code after
usereturns.
The promise must be stable
The most common error with use is creating the promise during render:
function UserProfile({ userId }) {
// Bug: a new promise on every render
const user = use(fetch(`/api/users/${userId}`).then((r) => r.json()));
return <h1>{user.name}</h1>;
}When a component suspends, React throws away its work, including any state. On the next attempt it calls the function again, which creates a new promise, which suspends again. The component never finishes. In a Client Component, React warns that it cannot use a promise created during render.
The promise has to outlive a single render. The earlier example stores promises in a module-level Map keyed by userId. This gives you a small cache. Two components that ask for the same user share one request.
That hand-rolled cache has gaps:
- Entries are never evicted, so data never refreshes.
- A rejected promise stays in the map, so retrying after an error returns the same failure.
- It is shared across every user in a server-rendered app.
This is the same gap that the earlier chapter on effect limitations described. A cache with keys, staleness rules, and invalidation is what a data library provides.
Rules that differ from other hooks
use looks like a hook, but it has looser rules:
- You can call it inside
ifstatements and loops, and after an earlyreturn. - You still call it only while a component or hook is rendering, not in event handlers or effects.
- You cannot call it inside a
try/catchblock. A suspended component works by interrupting render, and acatchwould intercept that. Handle rejections with an error boundary, or attach.catchto the promise to supply a fallback value.
use also reads context, with use(ThemeContext). The conditional-call rule applies to both uses.
Where the boundary goes
The position of a Suspense boundary decides what the user sees while waiting. It is a layout decision as much as a data decision.
- One boundary around the whole page shows a single spinner. The page appears all at once, when the slowest part is ready.
- Several boundaries around independent sections let each section appear as soon as its data arrives.
- A boundary nested inside another lets the outer content show first, with the inner fallback where its data is still pending.
Boundaries also interact with waterfalls. If a parent calls use(a) and then renders a child that calls use(b), the child cannot start until the parent resolves. Its request has not started yet, so the two requests run one after the other. To avoid this, start both promises before either component suspends. You can create them together in a parent or a loader, and pass them down as props.
function Dashboard({ userId }) {
const userPromise = getUser(userId);
const ordersPromise = getOrders(userId);
return (
<>
<Suspense fallback={<p>Loading profile...</p>}>
<Profile userPromise={userPromise} />
</Suspense>
<Suspense fallback={<p>Loading orders...</p>}>
<Orders ordersPromise={ordersPromise} />
</Suspense>
</>
);
}
function Profile({ userPromise }) {
const user = use(userPromise);
return <h2>{user.name}</h2>;
}
function Orders({ ordersPromise }) {
const orders = use(ordersPromise);
return <p>{orders.length} orders</p>;
}Both requests start when Dashboard renders. Each section reveals itself independently. This pattern assumes getUser and getOrders return stable, cached promises, as in the earlier Map example.
Avoiding a fallback on updates
Look back at the App example. When userId changes, UserProfile asks for a new promise and suspends again. Without care, React replaces the already visible profile with the Loading... fallback every time.
Wrapping the state update in startTransition marks it as non-urgent. React keeps the old UI on screen and prepares the new one in the background. isPending becomes true meanwhile, so you can dim the old content or disable the button. The fallback only appears the first time, when there is nothing to show yet. useDeferredValue gives a similar effect for a value that comes from props or input, such as a search term.
Suspense with a data library
A library solves the stable-promise problem for you. TanStack Query offers useSuspenseQuery, which suspends instead of returning isPending:
import { Suspense } from 'react';
import { useSuspenseQuery } from '@tanstack/react-query';
function UserName({ userId }) {
const { data } = useSuspenseQuery({
queryKey: ['user', userId],
queryFn: async ({ signal }) => {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
},
});
return <h1>{data.name}</h1>;
}
export function Page({ userId }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<UserName userId={userId} />
</Suspense>
);
}Here data is never undefined, so you skip the loading check. You keep the query key, caching, and invalidation from earlier chapters. Errors go to an error boundary instead of an error field.
Comparing the approaches
| Approach | Where loading state lives | Where errors go | Who owns the promise |
|---|---|---|---|
| `useEffect` and `useState` | In the component | In the component | The effect |
| `use` with a cache | In a `Suspense` boundary | To an error boundary | Your cache or a framework |
| `useSuspenseQuery` | In a `Suspense` boundary | To an error boundary | The query library |
Suspense is a way to display waiting states. It does not give you caching, deduplication, or retries. Those still need a cache, a library, or a framework underneath.
Exercise
A teammate writes const data = use(fetch(url).then((r) => r.json())); inside a Client Component, and the page stays on its Suspense fallback forever. Why does this happen, and what are two ways to fix it?
Show answer
The fetch runs during render, so every render attempt creates a new promise. The component suspends, React discards the render, and the next attempt creates another new promise, so it never finishes. Fix it by creating the promise outside the render of the suspending component and keeping it stable. For example, keep promises in a cache keyed by url, or use a library such as TanStack Query with useSuspenseQuery. A third option is to create the promise in a Server Component or a router loader and pass it down as a prop.
Exercise
Your page shows a profile and an order list. The order list component is rendered inside the profile component, and each calls use on its own promise created in render from a shared cache. Requests run one after the other. How do you make them run in parallel, and why does it work?
Show answer
Create both promises in a common parent before either child suspends, then pass them down as props, each inside its own Suspense boundary. Both requests start in the same render. Before this change, the order list's request did not start until the profile resolved, because the child was not rendered while its parent was suspended.