Sub topic 6
Handling rejected promises
This chapter assumes you can write function components, you know how promises settle, and you have seen use read a promise inside a Suspense boundary. It covers what use does when a promise rejects and the two ways to respond: an error boundary or a fallback value.
What happens on rejection
A promise has three states: pending, fulfilled, or rejected. use handles each one differently:
- Pending:
usesuspends the component, and the nearestSuspenseboundary shows its fallback. - Fulfilled:
usereturns the value and rendering continues. - Rejected:
usethrows the rejection reason during render.
The third case behaves like any error thrown while rendering. React looks for the nearest error boundary above the component and renders that boundary's fallback. If there is no error boundary, the error propagates up and can unmount the whole tree.
Option 1: an error boundary
An error boundary is a component that catches errors thrown by its children and renders a fallback instead. Place it outside the Suspense boundary so it can catch errors from the suspended subtree.
This example uses the react-error-boundary package:
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>
);
}While the promise is pending, the user sees "Waiting for message...". If it rejects, that text is replaced by "Could not load the message."
You don't need a package. A class component with getDerivedStateFromError works the same way:
import { Component } from 'react';
export class MessageErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}Use it in place of ErrorBoundary above, passing the same fallback prop.
Error boundaries still have to be classes, because React has no Hook for them. This is why most projects use react-error-boundary or a similar helper.
Option 2: a fallback value with catch
Sometimes a failure should not replace the UI with an error message. A missing message might just mean "show a default". In that case, attach .catch to the promise before it reaches use. The rejection becomes a fulfilled promise carrying a substitute value:
async function fetchMessage() {
const response = await fetch('/api/message');
if (!response.ok) {
throw new Error('Request failed');
}
return response.text();
}
const messagePromise = fetchMessage().catch(() => 'No message found.');The Message component from the previous example can read messagePromise without any changes. It never sees a rejection, so no error boundary is triggered.
Check response.ok yourself. fetch only rejects on network failures, so an HTTP 404 or 500 would otherwise resolve normally and your component would render the error page body as the message.
Why not try/catch?
It is tempting to wrap use in try/catch, as you would with await. That doesn't work. use is not supported inside a try/catch block.
function Message({ messagePromise }) {
// Wrong: use is not supported inside try/catch.
try {
const content = use(messagePromise);
return <p>{content}</p>;
} catch (error) {
return <p>Could not load the message.</p>;
}
}The reason is how use works. While the promise is pending, use suspends the component by throwing internally, and React relies on that throw reaching the Suspense boundary. A try/catch in the component could intercept it and break suspension. Handle errors outside the component that calls use: either with an error boundary above it or with .catch on the promise.
Choosing between the two
| Situation | Better choice |
|---|---|
| The failure should be visible to the user, with a message or a retry button | Error boundary |
| A sensible default exists and the user doesn't need to know about the failure | `.catch` with a fallback value |
| Several components under one section can fail the same way | One error boundary around the section |
| You want to log the error | Error boundary (for example its error callback) or logging inside `.catch` |
A .catch fallback hides the failure from React. If you use it, log the error inside the handler. Otherwise real outages look like normal "no data" results.
Common errors
- No error boundary at all. A rejection with nothing to catch it unmounts the tree. Add a boundary near any component that reads a network-backed promise.
- Error boundary placed inside
Suspense, around only the child. It will not catch errors from a promise read in a component it doesn't wrap. Put it around theSuspenseboundary as shown above. - Using
try/catcharounduse. Move the handling to.catchor an error boundary. - Treating HTTP errors as success. Check
response.okand throw, so the promise rejects. - Creating the promise during render. A new promise on every render can turn a failure into an endless cycle of new requests. The next chapter covers keeping promises stable.
Exercise
A component calls use(messagePromise), and the request behind it fails with a network error. You want the page to show "No message found." in place of the message, with no error screen. Where do you put the handling, and why can't you wrap the use call in try/catch?
Show answer
Attach .catch(() => 'No message found.') to the promise before it is passed to the component, so the promise fulfills with that string and use returns it. try/catch cannot be used because use is not supported inside a try/catch block. It relies on throwing to suspend the component, and a surrounding catch could interfere with that.
Exercise
You wrap a Message component in a Suspense boundary and add an ErrorBoundary around Message alone, inside the Suspense boundary. Is that placement a problem for catching rejections from use? What placement does this chapter recommend?
Show answer
The chapter recommends putting the ErrorBoundary outside the Suspense boundary, wrapping the whole Suspense subtree, so it catches the error thrown when the promise rejects. The key requirement is that the boundary must be an ancestor of the component calling use.