Sub topic 10
Suspense for Data Fetching and the use Hook
This chapter assumes you know function components, useState and useEffect, promises, and how React.lazy and Suspense work together for code. Here you will see the same boundary handle data.
The same boundary, a different cause
With React.lazy, a component suspends because its code has not arrived yet. React shows the nearest Suspense fallback until the import promise resolves. Data works the same way. If a component reads a promise that is still pending, it suspends, and the nearest boundary shows its fallback.
In React 19 the use hook is the supported way to read a promise during render. It returns the resolved value. If the promise is pending, use suspends the component. If the promise rejects, the error goes to the nearest error boundary.
import { Suspense, use } from 'react';
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return (
<ul>
{comments.map((c) => (
<li key={c.id}>{c.text}</li>
))}
</ul>
);
}
export function Post({ commentsPromise }) {
return (
<Suspense fallback={<p>Loading comments...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
);
}Comments has no loading state, no useEffect, and no isLoading flag. It is written as if the data were already there. The boundary above it handles the waiting.
How the pieces fit
When the promise settles, React retries rendering the suspended component. This time use returns the value.
Where the promise must come from
A common mistake is creating the promise inside the component that reads it:
function Comments({ postId }) {
// Wrong: a new promise on every render
const comments = use(fetch(`/api/posts/${postId}/comments`).then((r) => r.json()));
return <ul>{/* ... */}</ul>;
}A suspended component does not keep state between attempts. Each retry runs the function again and creates a new promise, which is also pending, so the component suspends forever. The promise needs a stable identity across renders. There are three reliable sources:
- A parent that is not suspending. Create the promise in a parent, as in the
Postexample above, and pass it down as a prop. - A Server Component. In a framework that supports them, a Server Component creates the promise and passes it to a Client Component. React tracks the promise across the boundary.
- A cache. A data library or your own cache returns the same promise for the same key.
A minimal cache looks like this:
const cache = new Map();
export function fetchComments(postId) {
if (!cache.has(postId)) {
cache.set(
postId,
fetch(`/api/posts/${postId}/comments`).then((r) => {
if (!r.ok) throw new Error(`Request failed: ${r.status}`);
return r.json();
})
);
}
return cache.get(postId);
}A real cache also needs invalidation and a way to retry after a failure. A rejected promise stays in this map, so a retry would get the same error. In practice, use a library that supports Suspense, or the data tools in your framework, instead of maintaining this yourself.
Rules specific to use
usecan be called inside conditions and loops. Other hooks cannot.usemust be called in a component or a custom hook, not in an event handler.usealso reads context:use(ThemeContext).- Prefer
useoverawaitin client components. Client components cannot beasync.
Avoiding waterfalls
If a component suspends, React does not render its children until it resumes. If the child then starts its own fetch, the requests run one after another. This is a waterfall. To avoid it, start requests as early as possible, for example in the parent or in a route loader, and pass the promises down. Sibling components under separate boundaries can then load in parallel.
Boundary placement also matters here. Several components under one boundary show a single fallback until all of them are ready. Separate boundaries let each section appear as soon as its own data arrives.
Combining with transitions and error boundaries
The earlier chapters on transitions and error boundaries still apply:
- Wrap the state change that triggers a new promise in
startTransition. React keeps the current content visible instead of falling back to the loading UI. - Place an error boundary outside the
Suspenseboundary so a failed request shows an error message.
Exercise
A component calls use(fetch('/api/user').then((r) => r.json())) directly in its body, and the page stays on the loading fallback forever. Why does this happen, and how would you fix it?
Show answer
Each time the component retries after suspending, it runs again and creates a new pending promise, so it never gets a resolved value. Create the promise outside the component, for example in a parent or a cache keyed by the request, and pass it in or look it up so the same promise is returned on every render.
Exercise
Two sibling components each read their own promise inside one shared Suspense boundary. What does the user see, and how can you change this so each appears as soon as its data is ready?
Show answer
The user sees one fallback until both promises resolve. Give each component its own Suspense boundary so each can replace its own fallback independently.