Sub topic 7
Keeping the Promise Stable Across Renders
The use API reads a promise during render. React can only do this safely if each render hands it the same promise object. This chapter explains what goes wrong when the promise changes between renders and the patterns that keep it stable.
It assumes you can write function components with props, use useState and useContext, and read async/await code. It also assumes you know that a Suspense boundary shows a fallback while something below it is not ready. Earlier chapters showed use(promise) inside <Suspense>. Here the focus is on where the promise comes from.
Why identity matters to `use`
React cannot look inside a pending promise, and it cannot pause a function component halfway through and resume it later. When use receives a pending promise, React does three things:
- It attaches handlers to the promise and records the promise's status on it.
- It throws away the current render attempt and shows the nearest Suspense fallback.
- When the promise settles, it renders the component again from the top.
On that second render, use must receive the same promise object. React then finds the recorded status, sees that the promise is fulfilled, and returns the value immediately. If it receives a different promise object, React has no record of it. The new promise is pending, so the component suspends again.
Two promises that will resolve to the same data are still two different objects, and React compares them by identity.
The failure: a promise created during render
The most common mistake is to create the promise inside the component that reads it.
import { Suspense, use } from 'react';
function Message() {
// A new promise is created on every render of Message.
const message = use(fetch('/api/message').then((response) => response.text()));
return <p>Here is the message: {message}</p>;
}
export default function App() {
return (
<Suspense fallback={<p>Waiting for message...</p>}>
<Message />
</Suspense>
);
}This code looks reasonable, but it never settles. The diagram shows the cycle.
In the broken path, the fetch finishes and React retries the render, but the retry calls fetch again. The new promise is pending, so React shows the fallback again. Depending on timing, you see a permanent fallback, repeated network requests, or both.
What you see in the console
React detects this pattern in development and logs a warning like this one:
A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.Treat this warning as a bug in your data flow. Do not try to silence it.
Why `useMemo` and `useState` in the same component do not rescue you
The obvious fix is to memoize the promise in the component that reads it.
function Message() {
const promise = useMemo(() => fetchMessage(), []);
const message = use(promise);
return <p>{message}</p>;
}This fails for two reasons.
First, when a component suspends on its first mount, React discards the work it did during that render, including hook state. On the retry the component mounts from scratch, so useMemo runs again and creates a new promise. The same applies to useState and useRef in that component.
Second, useMemo is a performance hint, not a guarantee. React may drop a memoized value and recompute it, so you should not rely on it for correctness.
The promise has to live somewhere that survives the suspension. That means one of these:
- A component above the Suspense boundary, which does not suspend, so its state is kept.
- A cache outside React, such as a module-level
Mapor a data library. - A Server Component, which passes the promise down as a prop.
Fix 1: create the promise above the Suspense boundary
A parent component outside the boundary keeps its state while its children suspend. It can create the promise, store it in state, and pass it down as a prop.
import { Suspense, startTransition, use, useState } from 'react';
function fetchUser(id) {
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(
(response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
);
}
function UserCard({ userPromise }) {
const user = use(userPromise);
return (
<p>
{user.name} ({user.email})
</p>
);
}
export default function App() {
// The lazy initializer runs once, on the first render of App.
const [userPromise, setUserPromise] = useState(() => fetchUser(1));
function selectUser(id) {
// Create the promise in an event handler, not during render.
const nextPromise = fetchUser(id);
startTransition(() => {
setUserPromise(nextPromise);
});
}
return (
<div>
<button onClick={() => selectUser(1)}>User 1</button>
<button onClick={() => selectUser(2)}>User 2</button>
<button onClick={() => selectUser(3)}>User 3</button>
<Suspense fallback={<p>Loading user...</p>}>
<UserCard userPromise={userPromise} />
</Suspense>
</div>
);
}Here is why this works:
Appis outside theSuspenseboundary, so it does not suspend and its state persists.userPromiseis the same object on every render ofAppuntil you replace it.UserCardsuspends, resolves, and retries with the same promise, sousereturns the value on the retry.- The
useStatelazy initializer (the function passed touseState) runs only on the first render, so the first fetch starts only once.
Replacing the promise inside a transition
When you click a button, the new promise is pending. Without a transition, React would replace the visible card with the fallback. Wrapping setUserPromise in startTransition tells React to keep showing the current UI until the new data is ready. A newly rendered boundary with no content yet still shows its fallback, but an already visible one does not flip back.
If you also want a pending indicator, use the isPending flag from useTransition.
import { Suspense, use, useState, useTransition } from 'react';
// fetchUser and UserCard are the same as in the previous example.
export default function App() {
const [userPromise, setUserPromise] = useState(() => fetchUser(1));
const [isPending, startTransition] = useTransition();
function selectUser(id) {
const nextPromise = fetchUser(id);
startTransition(() => {
setUserPromise(nextPromise);
});
}
return (
<div style={{ opacity: isPending ? 0.5 : 1 }}>
<button onClick={() => selectUser(2)}>Load user 2</button>
<Suspense fallback={<p>Loading user...</p>}>
<UserCard userPromise={userPromise} />
</Suspense>
</div>
);
}The call to fetchUser happens in the event handler, so each click creates exactly one promise. Creating the promise inside the startTransition callback also works, but computing it first makes it clearer that the fetch is not part of rendering.
Fix 2: cache the promise by key
State in a parent works when the parent knows which data to load. Often the component that needs the data is the one that knows the key, for example a UserCard that receives an id prop. In that case you can keep promises in a cache outside React, keyed by the inputs.
import { Suspense, use, useState } from 'react';
function fetchUser(id) {
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(
(response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
);
}
const userCache = new Map();
function getUser(id) {
let promise = userCache.get(id);
if (!promise) {
promise = fetchUser(id).catch((error) => {
// Do not keep failures: allow a later render to try again.
userCache.delete(id);
throw error;
});
userCache.set(id, promise);
}
return promise;
}
function UserCard({ id }) {
const user = use(getUser(id));
return <p>{user.name}</p>;
}
export default function App() {
const [id, setId] = useState(1);
return (
<div>
<button onClick={() => setId(id === 1 ? 2 : 1)}>Switch user</button>
<Suspense fallback={<p>Loading user...</p>}>
<UserCard id={id} />
</Suspense>
</div>
);
}getUser(id) returns the same promise object for the same id, however many times UserCard renders. Switching back to a user you have already loaded returns the already fulfilled promise, so use returns the value immediately with no fallback.
React's own documentation says that creating promises in Client Components is not supported outside a Suspense-compatible library or framework. A hand-written cache like this one gives you stable identity, which is the property use needs. It does not give you the rest of what a data library provides. You take on these responsibilities yourself:
- Invalidation. Nothing refreshes stale data. You must clear or replace entries when the data changes.
- Memory. The
Mapgrows for the life of the page unless you evict entries. - Errors. Without the
catchabove, a rejected promise stays cached and every later render rethrows the same error. - Server rendering. A module-level cache on a server is shared by every request, so one user's data can leak into another user's page. Do not use a module-level
Mapfor per-user data in server-rendered code.
For anything beyond a small demo, use a library or framework that provides Suspense-compatible caching rather than maintaining this code.
Fix 3: let a Server Component create the promise
In a framework that supports Server Components, the server can start the fetch and pass the promise to a Client Component as a prop. React serializes the promise and streams the result to the browser. On the client, the promise passed through props keeps its identity across re-renders, which solves the problem without a cache of your own.
import { Suspense } from 'react';
import { Message } from './Message';
async function fetchMessage() {
const response = await fetch('/api/message');
if (!response.ok) {
throw new Error('Request failed');
}
return response.text();
}
export default function App() {
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}This is a sketch. Message must be a Client Component that reads the prop with use, and the fetch URL has to resolve on the server. The next chapter covers the details.
Comparing the options
| Approach | Where the promise lives | Good for | Main cost |
|---|---|---|---|
| State in a parent above the boundary | `useState` in a non-suspending component | Data chosen by user actions, such as a selected item | Parent must know what to load and when |
| Cache keyed by input | Module-level `Map` or data library | Many components asking for the same data by key | You own invalidation, memory, and error handling |
| Server Component passes a promise | Created on the server, passed as a prop | Initial page data in a framework with Server Components | Needs framework support |
| Promise created during render | Nowhere stable | Nothing | Suspends again on every retry |
A checklist for stable promises
Before you ship code that calls use on a promise, check each item:
- The promise is not created in the same component that calls
use, unless it comes from a cache that returns the same object for the same key. - A promise that comes from state is created in an event handler or in a lazy
useStateinitializer, never in the render body. - The component that owns the promise is outside the Suspense boundary that wraps the reader.
- Updates that replace the promise go through
startTransition, so the screen does not revert to the fallback. - Rejected promises are either caught for a fallback value or left to reach an error boundary, and a cache does not keep a rejection forever.
Summary of the working model
usetracks a promise by object identity. The same object means the same pending or finished work.- A promise created during render in a Client Component is new on every render, so the component suspends on every retry.
- State and memoization inside the suspending component are discarded on the first mount, so they cannot hold the promise.
- Put the promise in a parent above the boundary, in a cache keyed by input, or on the server.
- Replace promises inside transitions so existing content stays on screen.
Exercise
A teammate writes const data = use(useMemo(() => fetchData(id), [id])); inside a component that is wrapped in <Suspense>. The page shows the fallback for a long time and the network tab shows repeated requests for the same data. Explain why, and describe two fixes.
Show answer
On the first mount the component suspends, and React discards the hook state of a component that suspended before it ever committed. The useMemo value is lost, so the retry calls fetchData(id) again and creates a new pending promise. That promise suspends the component again, and the cycle repeats with a new request each time. useMemo is also only a performance hint, so it cannot guarantee identity anyway. Two fixes: (1) Create the promise in a parent component that sits outside the Suspense boundary, for example in useState or an event handler, and pass it down as a prop. (2) Use a cache keyed by id, such as a module-level Map or a Suspense-compatible data library, so getData(id) returns the same promise object for the same id.
Exercise
In the keyed-cache example, the .catch handler calls userCache.delete(id) before rethrowing. What happens if you remove the delete line, and a request for user 2 fails once because of a network error?
Show answer
The rejected promise stays in the cache under key 2. Every later render that calls getUser(2) receives that same rejected promise, so use throws the same error each time and the error boundary can never recover by retrying. With the delete line, the failed entry is removed, so a later render (for example after the user clicks a retry button that resets the error boundary) calls fetchUser(2) again and creates a fresh promise.
Exercise
In the state-in-a-parent example, why does the user see the old card, rather than the fallback, when they click a button that calls setUserPromise inside startTransition? What would change if you called setUserPromise(nextPromise) without startTransition?
Show answer
A transition marks the update as non-urgent. When the new UserCard suspends on the new pending promise, React keeps the previously committed UI on screen instead of replacing an already visible boundary with its fallback, and it commits the new UI when the promise resolves. Without startTransition, the update is urgent, so React shows the Loading user... fallback as soon as UserCard suspends on the new promise, and the old card disappears until the data arrives.