Sub topic 14
Suspense and the use hook
This chapter assumes you know the effect-based fetching pattern from earlier chapters, including loading and error states and why effects need cleanup. It also assumes React 19, where the use hook is available.
What changes
In an effect, the component renders first, then fetches, then renders again with data. The component has to track isLoading and error itself. Suspense reverses this. The component asks for a value, and if the value isn't ready, React pauses that part of the tree and shows a fallback instead. The loading state moves out of the component and into a Suspense boundary above it.
The use hook
use reads the value of a promise during render. It behaves in one of three ways:
- If the promise has resolved,
usereturns the value. - If the promise is still pending,
usesuspends the component. React shows the nearestSuspensefallback and retries when the promise settles. - If the promise rejects, the error propagates to the nearest error boundary.
Unlike other hooks, use can be called inside conditionals and loops. It still has to be called while a component or hook is rendering.
A working example
The promise must be stable across renders. If you create a new promise inside the suspending component, every retry creates another promise, and the component never finishes. This example creates the promise in the parent and caches it by user id.
import { Suspense, use } from 'react';
const userCache = new Map();
function getUser(userId) {
if (!userCache.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();
});
userCache.set(userId, promise);
}
return userCache.get(userId);
}
function UserName({ userPromise }) {
const user = use(userPromise);
return <h1>{user.name}</h1>;
}
export default function UserPage({ userId }) {
const userPromise = getUser(userId);
return (
<Suspense fallback={<p>Loading...</p>}>
<UserName userPromise={userPromise} />
</Suspense>
);
}UserName has no state, no effect, and no loading check. When userId changes, getUser returns a different promise, and the fallback appears while it loads.
Errors and waterfalls
A rejected promise does not show in the component. Wrap the Suspense boundary in an error boundary, such as one from the react-error-boundary package, to render an error message.
Suspense does not remove request waterfalls. If a component suspends, its children don't render, so a child can't start its own fetch until the parent resolves. Start independent requests early, in the same parent, and pass the promises down.
You can also place several Suspense boundaries in one page. Each section then loads and appears independently of the others.
Who owns the promise
Suspense and use define how a component waits, not where promises come from or how they are cached. Three sources are practical:
| Source | Who caches the promise |
|---|---|
| Hand-written cache, as above | You |
| A data library with Suspense support | The library |
| A framework or Server Component | The framework |
The next chapter shows the third option, where the server does the waiting.
Exercise
Why does calling use(fetch('/api/users/1')) directly inside a component cause trouble, and how do you fix it?
Show answer
Each render creates a new promise. When the component suspends and React retries, it creates another new pending promise, so the component never gets a resolved value. The fix is to create the promise outside the suspending component, for example in a parent or a cache keyed by the request, so the same promise is passed in on every render.