Sub topic 10
Suspense for Data Fetching and the use Hook
This chapter assumes you know function components, useState and useEffect, promises and async/await, and how React.lazy and Suspense work for code. You should also know what a Suspense boundary is and how a fallback is shown. Here you will apply the same boundary to data.
Why Suspense can wait for data
With React.lazy, a component can't render until its code has arrived. React handles that by pausing rendering at that component, showing the nearest Suspense fallback, and trying again when the promise settles. The mechanism does not care what the promise is waiting for. It can be a JavaScript chunk, or it can be a JSON response.
In React 19, the use hook lets a component read a promise directly during render. If the promise is still pending, the component suspends. If it has resolved, use returns the value. If it has rejected, the error is thrown to the nearest error boundary.
Compare this with the usual useEffect pattern:
import { useEffect, useState } from 'react';
function CommentsWithEffect({ postId }) {
const [comments, setComments] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
fetch(`/api/posts/${postId}/comments`)
.then((res) => res.json())
.then((data) => {
if (!cancelled) setComments(data);
})
.catch((err) => {
if (!cancelled) setError(err);
});
return () => {
cancelled = true;
};
}, [postId]);
if (error) return <p>Failed to load comments.</p>;
if (!comments) return <p>Loading comments...</p>;
return (
<ul>
{comments.map((c) => (
<li key={c.id}>{c.text}</li>
))}
</ul>
);
}Every component written this way tracks its own loading and error state, and each one starts fetching only after it has rendered and the effect has run. With use, the component only describes what to show once data exists. Loading is handled by a Suspense boundary above it, and errors by an error boundary above that.
Reading a promise with use
The use hook takes a promise and returns its resolved value:
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 receives a promise as a prop. It does not create the promise. Where the promise comes from matters a great deal, as the next sections show.
use differs from other hooks in one way. You can call it inside conditionals and loops, and after an early return, as long as it is called inside a component or a custom hook. The rules about calling useState and useEffect at the top level do not apply to use.
use can also read context: use(ThemeContext) works like useContext(ThemeContext), with the added freedom to be called conditionally. This chapter focuses on promises.
The promise must be stable
A suspended component is thrown away and rendered again from the start when the promise settles. If the component creates a new promise on each render, every retry creates another pending promise, which suspends again, and the component never finishes.
import { use } from 'react';
// Broken: a new promise is created on every render attempt.
function Comments({ postId }) {
const comments = use(fetch(`/api/posts/${postId}/comments`).then((r) => r.json()));
return <p>{comments.length} comments</p>;
}React warns about this in development. The fix is to create the promise somewhere that survives re-renders, then pass it in or look it up from a cache. There are three common places:
| Source of the promise | How it stays stable | Typical use |
|---|---|---|
| A parent component's props | The parent creates it once, for example in an event handler or a Server Component | Passing a promise from a Server Component to a Client Component |
| A cache keyed by input | A module-level `Map` or a library cache returns the same promise for the same key | Client-side fetching without a library |
| A data library or framework | The library caches requests and exposes Suspense-compatible APIs | Production applications |
Creating the promise in a parent with useMemo is not a reliable fix. React may discard memoized values, and a suspended first render has no committed state to keep them in. Treat useMemo as a performance hint, not a guarantee.
A minimal client-side cache
The following module caches one promise per URL. It is intentionally small, to show the idea. It has no expiry, no invalidation, and no limit on size.
import { Suspense, use } from 'react';
const cache = new Map();
function fetchJson(url) {
if (!cache.has(url)) {
const promise = fetch(url).then((res) => {
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
}
return res.json();
});
cache.set(url, promise);
}
return cache.get(url);
}
function UserName({ userId }) {
const user = use(fetchJson(`/api/users/${userId}`));
return <strong>{user.name}</strong>;
}
export function UserBadge({ userId }) {
return (
<Suspense fallback={<span>Loading user...</span>}>
<UserName userId={userId} />
</Suspense>
);
}Calling fetchJson during render is fine here, because it returns the same promise for the same URL. The first call starts the request. Later calls, including the retry after the promise resolves, get the cached promise, and use returns its value immediately.
Note that a rejected promise stays in this cache. After one network failure, every later read of that URL throws the same error. A real cache must remove failed entries so a retry can fetch again. This is one reason to prefer a library for anything beyond a demo.
How a component suspends
The flow below shows what happens when Comments first renders with a pending promise.
While the component is suspended, React does not commit its output. Work done in the suspended render, including local state created in that attempt, is not kept. Components outside the boundary stay as they are.
Errors from rejected promises
A rejected promise makes use throw during render. That is the same situation as a failed lazy import, so the same tool applies: an error boundary placed outside the Suspense boundary.
import { Component, Suspense, use } from 'react';
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return <p>{comments.length} comments</p>;
}
export function CommentsSection({ commentsPromise }) {
return (
<ErrorBoundary fallback={<p>Could not load comments.</p>}>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
</ErrorBoundary>
);
}Do not wrap use in try/catch. use signals both "still loading" and "failed" by throwing, and a catch block would intercept React's own suspension signal. For a fallback value on failure, attach .catch() to the promise before passing it in.
Avoiding request waterfalls
Suspense does not make data load faster. It changes where you write the waiting logic. A request waterfall happens when one request cannot start until another has finished.
Suspense makes one kind of waterfall easy to create. If a parent suspends on its own data, its children are not rendered until the data arrives. If those children then start their own fetches, those fetches begin late.
import { Suspense, use } from 'react';
function Profile({ userId }) {
const user = use(fetchJson(`/api/users/${userId}`));
return (
<div>
<h2>{user.name}</h2>
{/* Posts does not render until Profile has its data. */}
<Posts userId={userId} />
</div>
);
}
function Posts({ userId }) {
const posts = use(fetchJson(`/api/users/${userId}/posts`));
return <p>{posts.length} posts</p>;
}
export function ProfilePage({ userId }) {
return (
<Suspense fallback={<p>Loading profile...</p>}>
<Profile userId={userId} />
</Suspense>
);
}Here the posts request starts only after the user request ends, even though it needs only userId. To fix this, start both requests before either component suspends. For example, create both promises in a parent or route-level function and pass them down:
import { Suspense, use } from 'react';
function Profile({ userPromise, postsPromise }) {
const user = use(userPromise);
return (
<div>
<h2>{user.name}</h2>
<Suspense fallback={<p>Loading posts...</p>}>
<Posts postsPromise={postsPromise} />
</Suspense>
</div>
);
}
function Posts({ postsPromise }) {
const posts = use(postsPromise);
return <p>{posts.length} posts</p>;
}
export function ProfilePage({ userPromise, postsPromise }) {
return (
<Suspense fallback={<p>Loading profile...</p>}>
<Profile userPromise={userPromise} postsPromise={postsPromise} />
</Suspense>
);
}Both promises exist before the first render, so both requests run in parallel. The inner boundary also lets the user's name appear before the posts finish.
This is the same idea as preloading a lazy component: start the work as early as you can, and let Suspense control only what the user sees.
Combining use with transitions
The earlier chapter on transitions showed that wrapping a state update in startTransition keeps the current UI on screen while a lazy component loads. The same applies to data. Suppose a user picks another post. If the new commentsPromise is set in a normal state update, the boundary swaps the visible comments for the fallback. In a transition, React keeps the old comments visible until the new ones are ready.
import { Suspense, use, useState, useTransition } from 'react';
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return (
<ul>
{comments.map((c) => (
<li key={c.id}>{c.text}</li>
))}
</ul>
);
}
export function PostViewer({ postIds, loadComments }) {
const [commentsPromise, setCommentsPromise] = useState(() =>
loadComments(postIds[0])
);
const [isPending, startTransition] = useTransition();
function selectPost(id) {
startTransition(() => {
setCommentsPromise(loadComments(id));
});
}
return (
<div>
{postIds.map((id) => (
<button key={id} onClick={() => selectPost(id)}>
Post {id}
</button>
))}
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
</div>
</div>
);
}The promise is created in the event handler, not during render, so it is stable. It is stored in state, so it survives re-renders. The Suspense boundary only shows its fallback on the first load, because later updates happen inside a transition.
Server Components and promises as props
A common use of use is receiving a promise from a Server Component. The server starts the request and passes the unresolved promise to a Client Component. The server does not wait for the data before sending the rest of the page. The Client Component reads the promise with use, and the surrounding Suspense boundary shows a fallback until the data arrives.
This avoids the stable-promise problem, since React serializes the promise across the server boundary and keeps it consistent. It also needs a framework or a bundler setup that supports Server Components, so you will usually reach for it through a framework rather than configure it yourself. The next chapter looks at how Suspense behaves on the server in general.
When to use this, and when not to
- Use
usewith promises that come from a framework, a data library, or a cache you control. - Do not create promises inside the component that reads them.
- Keep
useEffectfetching for simple cases, or when you want no boundary involved. It still works. - Place error boundaries outside Suspense boundaries, and decide how large each loading region should be, using the same placement rules as for lazy components.
Exercise
A component calls use(fetch('/api/items').then((r) => r.json())) directly in its body. The page shows the fallback forever and the network panel shows many requests. Why does this happen, and how would you fix it?
Show answer
Each render attempt creates a new promise. When the component suspends and React retries it, the retry creates yet another pending promise, so the component suspends again and never completes. Create the promise outside the render of the reading component: in a parent or event handler and pass it as a prop, or look it up from a cache that returns the same promise for the same key. Also remove rejected entries from the cache so failures can be retried.
Exercise
You have a Profile component that reads the user with use, and inside it a Posts component that fetches posts with its own use call. How can you remove the waterfall between the two requests?
Show answer
Start both requests before either component suspends, for example in a parent or at the route level. Pass userPromise and postsPromise as props. Both requests then run in parallel. Wrapping Posts in its own Suspense boundary also lets the user data appear before the posts arrive.