Sub topic 3
Handling Rejected Promises with React `use`
Assume you know function components, props, promises, useContext, and the basic role of Suspense. React’s use API reads a promise during rendering. A pending promise pauses that part of the tree. A rejected promise throws its error.
Handling rejected promises
Put an error boundary above the Suspense boundary. An error boundary is a component that displays fallback UI when a child throws.
import { Suspense, use } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>{message}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>Could not load the message.</p>}>
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}A rejected promise reaches the nearest error boundary. If a fallback value is more useful, handle the rejection before passing the promise to use:
const messagePromise = fetch('/api/message')
.then((response) => {
if (!response.ok) throw new Error('Request failed');
return response.text();
})
.catch(() => 'No message found.');Do not put use inside try/catch. React must control how it suspends and reports errors.
Keeping the promise stable across renders
A Client Component should not create a new promise during every render. Each render would give use a different promise, which can cause repeated requests or an endless loading state. Create the promise outside the component, cache it, or receive it through props.
flowchart TD
A[Stable promise] --> B[use reads it]
B --> C{Promise state}
C -->|pending| D[Suspense fallback]
C -->|fulfilled| E[Render value]
C -->|rejected| F[Error boundary or fallback value]Streaming from Server to Client
A Server Component can start a request and pass the unresolved promise to a Client Component. Suspense then lets other page content render while the client component waits.
// Server Component
const messagePromise = fetch('/api/message').then((response) => response.text());
return (
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);Choosing the right tool
Use use for promises in components and for conditional context reads. Use useContext when reading context unconditionally with normal Hook rules. Use await in an async Server Component when that component should wait before returning its result.
Exercise
What should handle a rejected promise passed to use?
Show answer
Use an error boundary, or attach catch to the promise and provide a fallback value.