Sub topic 7
Keeping the promise stable across renders
This chapter assumes you have read a promise with use inside a Suspense boundary and know the basics of useState and props. It explains why the promise you pass to use must keep the same identity from one render to the next, and how to arrange that.
Why identity matters
use does not read the promise's value directly. It looks up the state of the promise object you give it: pending, fulfilled, or rejected. React keeps that state on the promise itself. If you pass use a different promise on the next render, React has no record of it, so the promise counts as pending again.
Suppose you write this in a Client Component:
import { use } from 'react';
function Message({ id }) {
// Wrong: a new promise on every render
const messagePromise = fetch(`/api/messages/${id}`).then((r) => r.json());
const message = use(messagePromise);
return <p>{message.text}</p>;
}The first render creates promise A, and use suspends. When A resolves, React renders Message again. That render calls fetch again and creates promise B. B is pending, so use suspends again. The component never gets past use, and it sends a request on every attempt.
React detects this pattern and logs a warning that a component was suspended by an uncached promise. The message says that creating promises inside a Client Component or Hook is not yet supported, except through a Suspense-compatible library or framework.
The rule
The promise must come from somewhere that outlives the render. The table lists the common sources.
| Where the promise is created | Stable? | Notes |
|---|---|---|
| Inside the component body that calls `use` | No | New promise every render. |
| In a Server Component, passed as a prop | Yes | The standard approach with a framework. |
| In state of a parent component | Yes | The parent must not be the component that suspends. |
| In a module-level cache keyed by input | Yes | You manage invalidation and errors yourself. |
| In a Suspense-compatible library | Yes | The library caches for you. |
The next sections cover the Client Component options.
Option 1: hold the promise in a parent's state
A parent can create the promise once and pass it down. State persists across renders, so the identity stays the same. The parent must sit outside the Suspense boundary. If the component that owns the state is also the one that suspends, React can discard its state during the first mount.
import { Suspense, use, useState } from 'react';
function fetchMessage(id) {
return fetch(`/api/messages/${id}`).then((response) => {
if (!response.ok) {
throw new Error('Request failed');
}
return response.json();
});
}
function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>{message.text}</p>;
}
export function MessageViewer() {
const [id, setId] = useState(1);
const [messagePromise, setMessagePromise] = useState(() => fetchMessage(1));
function showNext() {
const nextId = id + 1;
setId(nextId);
setMessagePromise(fetchMessage(nextId));
}
return (
<>
<button onClick={showNext}>Next message</button>
<Suspense fallback={<p>Loading message {id}...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</>
);
}MessageViewer creates a new promise only when the user clicks, inside an event handler. Re-renders for any other reason reuse the stored promise. Message suspends, but it owns no state, so nothing is lost.
In development with Strict Mode, React calls the useState initializer twice. You may see two requests for the first message. That is expected and does not happen in production.
Option 2: a cache keyed by input
When many components might ask for the same data, store promises in a cache. The first caller starts the request, and every later caller with the same key gets the same promise.
const messageCache = new Map();
export function getMessage(id) {
if (!messageCache.has(id)) {
const promise = fetch(`/api/messages/${id}`)
.then((response) => {
if (!response.ok) {
throw new Error('Request failed');
}
return response.json();
})
.catch((error) => {
messageCache.delete(id);
throw error;
});
messageCache.set(id, promise);
}
return messageCache.get(id);
}A component can now call use(getMessage(id)) and get the same promise on every render for that id.
This sketch leaves some problems unsolved:
- Entries never expire, so the data can go stale.
- The cache grows without limit unless you add eviction.
- A module-level
Mapon a server is shared by all users. Never cache user-specific data this way during server rendering.
The .catch handler removes a failed entry so that a later render can retry. Without it, the rejected promise would stay cached and every caller would keep getting the same error.
Option 3: let a server or library own it
The most reliable fix is to avoid creating promises in Client Components. A Server Component can start the fetch and pass the promise as a prop. A Suspense-compatible data library, or a framework with built-in data loading, manages caching and invalidation for you. The next chapter covers the server approach.
Common mistakes
- Calling a function that returns a new promise directly inside
use(...)in a Client Component. - Storing the promise in state of the component that suspends, then losing it when the first mount is discarded.
- Creating a promise in the render body "just once" with a plain variable. Local variables are recreated on every call.
- Caching rejected promises, which makes errors permanent.
Exercise
A Client Component calls use(fetchUser(userId)) and the page shows the fallback forever while the network tab shows repeated requests. Explain the cause and give one fix.
Show answer
fetchUser(userId) creates a new promise on every render. Each time the previous promise resolves, React re-renders the component, which creates a new pending promise, so use suspends again and the cycle repeats. To fix it, create the promise somewhere stable. For example, create it in a parent's state or in an event handler and pass it down as a prop. You could also look it up in a cache keyed by userId, or pass it from a Server Component.