Sub topic 3
Reading a promise with use
This chapter assumes you can write function components with props, use useState, and work with JavaScript promises and async functions. It also assumes you know that a Suspense boundary shows a fallback while something below it is not ready. Here you will use use to read the value of a promise inside a component.
What use does with a promise
use is an API in React 19. You pass it a promise, and it returns the value that the promise resolves to.
const message = use(messagePromise);The line looks synchronous, but the promise may not have settled yet. When it hasn't, use suspends the component. Suspending means React stops rendering that component, keeps the work done so far, and shows the fallback of the nearest Suspense boundary above it. When the promise resolves, React renders the component again. This time use returns the resolved value and rendering continues.
use differs from await in that it does not pause a function. The component function runs from the top again after the promise settles. Code before the use call can therefore run more than once, so keep it free of side effects.
A first example
The component below receives a promise as a prop and reads it with use. A Suspense boundary around it supplies the fallback.
import { Suspense, use } from 'react';
function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>Here is the message: {message}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}To run it, something above MessageContainer must create the promise once. This version creates it at module level, which keeps the example simple:
import { createRoot } from 'react-dom/client';
import { MessageContainer } from './MessageContainer';
const messagePromise = new Promise((resolve) => {
setTimeout(() => resolve('Hello from a promise'), 1500);
});
createRoot(document.getElementById('root')).render(
<MessageContainer messagePromise={messagePromise} />
);For 1.5 seconds you see "Waiting for message...". Then the paragraph replaces it.
The next diagram shows the sequence of events.
Where to put the Suspense boundary
The boundary decides how much of the page is replaced by a fallback. If you wrap the whole page, the whole page disappears while one promise is pending. If you wrap only the component that calls use, the rest stays visible. Place the boundary as close to the suspending component as the design allows.
A component can read several promises. It suspends on the first one that is pending. In this example the second promise has probably been running the whole time, because it was created by the parent:
function Profile({ userPromise, postsPromise }) {
const user = use(userPromise);
const posts = use(postsPromise);
return (
<section>
<h2>{user.name}</h2>
<p>{posts.length} posts</p>
</section>
);
}Create both promises before either is read. If the second promise were created only after the first resolved, the two requests would run one after the other.
When the promise rejects
If the promise rejects, use throws the rejection reason during render. The nearest error boundary then renders its fallback. Place an error boundary outside the Suspense boundary:
import { Suspense, use } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
function Message({ messagePromise }) {
const content = use(messagePromise);
return <p>Here is the message: {content}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>Could not load the message.</p>}>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}You can also supply a fallback value by attaching catch to the promise before passing it down:
const messagePromise = new Promise((resolve, reject) => {
// ...
}).catch(() => 'No message found.');Common errors
- Creating the promise in the component that reads it. In a Client Component, a promise created during render is a new promise on every render. Each render suspends again on a pending promise, and React warns that the component suspended on an uncached promise. Create the promise in a parent, outside the component, or in a cache or library that returns the same promise for the same input. The chapter on promise identity covers this in detail.
- Marking the component
async. A Client Component cannot be anasyncfunction. Read the promise withuseinstead. - Missing Suspense boundary. Without a boundary, there is no fallback to show while the promise is pending. Add a
Suspenseboundary above the component that callsuse. - Expecting
useto start the work.useonly reads a promise. The request begins when whoever created the promise runs it.
| Situation | Result of `use(promise)` |
|---|---|
| Promise is pending | Component suspends, nearest Suspense fallback shows |
| Promise has resolved | Returns the resolved value |
| Promise has rejected | Throws the reason, nearest error boundary renders |
Exercise
A Client Component named Comments contains const comments = use(fetchComments(postId)); and sits inside a Suspense boundary. The fallback flashes repeatedly and the page never shows the comments. What is the cause, and how would you fix it?
Show answer
fetchComments(postId) runs on every render, so each render creates a new pending promise. The component suspends on it, and when React retries, it creates yet another promise. Fix it by creating the promise outside the component's render, for example in a parent that passes it down as a prop, or through a cache that returns the same promise for the same postId. Then Comments calls use(commentsPromise) on a stable promise.
Exercise
Where should you place the ErrorBoundary relative to the Suspense boundary so that a rejected promise shows an error message, and why can't you handle the rejection with try/catch around use?
Show answer
Put the ErrorBoundary outside the Suspense boundary so it catches errors thrown by components inside it. A try/catch around use does not work because use is not supported inside a try/catch block. Use an error boundary or attach .catch to the promise to provide a fallback value.