Sub topic 1
Reading Promises and Context with the React `use` API
Prerequisites
Assume you know function components, props, useState, useContext, JavaScript promises, and the basic purpose of Suspense. This chapter uses React 19 syntax.
What `use` Does and How It Differs from Other Hooks
use reads a value during rendering. It can read a promise or a context object.
For a promise, use returns the fulfilled value. While the promise is pending, React pauses that component and shows the nearest Suspense fallback. If the promise rejects, React sends the error to the nearest error boundary.
Unlike traditional Hooks, use may be called inside a condition, loop, or after an early return. useState stores component state, useEffect runs side effects, and useContext reads context only. Use useContext when you specifically need context and do not need its conditional calling behavior.
Suspense: The Fallback That `use` Relies On
Suspense provides temporary UI while a child is not ready. A use call that reads a pending promise causes the nearest boundary to render its fallback.
Reading a Promise with `use`
Pass a promise into the component instead of awaiting it there. The promise must remain stable across renders. A Server Component, cache, or parent can create it.
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>
);
}When messagePromise is pending, Message does not finish rendering. React displays Waiting for message.... When the promise fulfills, React retries the component and message contains its result.
Do not create the promise inside Message during a Client Component render. Each render would create a new promise, which can cause repeated suspension or requests.
Exercise
What does the Suspense boundary display while messagePromise is pending?
Show answer
It displays <p>Waiting for message...</p> from the boundary's fallback prop.