Sub topic 9
Using react-error-boundary with function components
This chapter assumes you can write class-based boundaries from the earlier chapters and know which errors boundaries do not catch. It also assumes you are comfortable with hooks, Promises, and async/await.
React has no hook for getDerivedStateFromError or componentDidCatch. A boundary must be a class component, even in a codebase that is otherwise all function components. The react-error-boundary package gives you one maintained class. You use it as a normal component, and it adds reset behavior and a hook for sending errors from handlers and async code.
Installing and using the basic boundary
npm install react-error-boundaryThe package exports ErrorBoundary, useErrorBoundary, and withErrorBoundary. The simplest use matches the hand-written boundary you built earlier:
import { ErrorBoundary } from "react-error-boundary";
function App() {
return (
<ErrorBoundary fallback={<p>Something went wrong.</p>}>
<Profile />
</ErrorBoundary>
);
}The scope is the same as for any boundary. It catches errors thrown while rendering, in lifecycle methods, and in constructors of its descendants. It does not catch errors from event handlers, async code, or server-side rendering.
Three ways to provide a fallback
The library offers three props for the fallback. Use one of them per boundary. If you pass more than one, fallbackRender takes priority, then FallbackComponent, then fallback.
| Prop | Type | Receives error and reset function? | Use it when |
|---|---|---|---|
| `fallback` | React element | No | The message is static and needs no retry button |
| `FallbackComponent` | Component | Yes, as props | The fallback is a reusable component that may use hooks |
| `fallbackRender` | Function returning an element | Yes, as an argument | You want an inline fallback that closes over local variables |
Both FallbackComponent and fallbackRender receive an object with two fields: error and resetErrorBoundary.
import { ErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function Page() {
return (
<ErrorBoundary FallbackComponent={Fallback}>
<Profile />
</ErrorBoundary>
);
}The same fallback written inline:
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => (
<div role="alert">
<p>Could not load: {error.message}</p>
<button onClick={resetErrorBoundary}>Retry</button>
</div>
)}
>
<Profile />
</ErrorBoundary>error.message is convenient during development. In production, avoid showing raw messages to users, because they may expose internal details. Show a friendly sentence and log the real error instead.
Resetting the boundary
When a boundary is showing its fallback, resetting it clears the stored error and renders the children again. If the cause is gone, the subtree works. If it is not, the boundary catches the error again.
The library gives you two ways to reset.
- Manual reset. Call
resetErrorBoundary()from the fallback, usually from a "Try again" button. - Automatic reset with
resetKeys. Pass an array of values. When any value changes between renders, the boundary resets itself.
resetKeys is the better fit when the error depends on data. If a profile fails for user 7, switching to user 8 should not leave the user staring at an error.
import { ErrorBoundary } from "react-error-boundary";
function ProfilePage({ userId }) {
return (
<ErrorBoundary
FallbackComponent={Fallback}
resetKeys={[userId]}
onReset={(details) => {
console.log("boundary reset because of", details.reason);
}}
>
<Profile userId={userId} />
</ErrorBoundary>
);
}The onReset callback runs on either kind of reset. Its details.reason is "imperative-api" for a manual reset and "keys" for an automatic one. Use it to clear state that caused the failure, such as a cache entry or a query result, before the children render again.
The keys are compared item by item with Object.is. Put primitives in the array, such as ids and counters. An object or array created inline on each render looks changed every time, so the boundary would reset on every render and could loop.
The library resets on a key change only if the boundary already held an error before that change. An error thrown in the same render where the keys changed is not wiped out immediately. This prevents an infinite cycle of reset, throw, reset.
Sending handler and async errors to the boundary
A boundary cannot see an error thrown inside onClick or after an await. The useErrorBoundary hook closes that gap. It returns two functions:
showBoundary(error)hands an error to the nearest boundary above the calling component, which then shows its fallback.resetBoundary()resets that same boundary from inside the subtree.
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
async function save(documentId) {
const response = await fetch(`/api/documents/${documentId}`, {
method: "PUT",
});
if (!response.ok) {
throw new Error(`Save failed with status ${response.status}`);
}
}
function SaveButton({ documentId }) {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save(documentId);
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}
function Editor({ documentId }) {
return (
<ErrorBoundary FallbackComponent={Fallback} resetKeys={[documentId]}>
<SaveButton documentId={documentId} />
</ErrorBoundary>
);
}Internally, the hook stores the error in state and rethrows it during the next render. That turns the handler error into a render error, which boundaries do catch.
Decide first whether a boundary-level fallback is the right response. A failed save is often better shown as an inline message next to the button, with the form still on screen. Replacing a whole editor with an error panel can throw away the user's unsaved work. Use showBoundary for failures that make the subtree unusable, such as a data load that the screen cannot work without.
useErrorBoundary throws if there is no ErrorBoundary above the component. That is intentional, since showBoundary would have nowhere to send the error.
Wrapping a component with withErrorBoundary
If you prefer to attach a boundary where a component is defined, use the higher-order component withErrorBoundary. It takes the component and the same props you would pass to ErrorBoundary.
import { withErrorBoundary } from "react-error-boundary";
function Chart({ data }) {
return <pre>{JSON.stringify(data)}</pre>;
}
const SafeChart = withErrorBoundary(Chart, {
fallback: <p>The chart could not be displayed.</p>,
});Every use of SafeChart now has its own boundary. This is handy for widgets that appear in many places. The cost is that the boundary is hidden from the call site, so a reader of <SafeChart /> cannot see where the error is contained.
Reporting errors with onError
The onError prop runs when the boundary catches a render error. It receives the error and an info object with componentStack, the same data componentDidCatch gives you.
import { ErrorBoundary } from "react-error-boundary";
function logError(error, info) {
// Replace with a call to your logging service.
console.error("Caught by boundary:", error, info.componentStack);
}
function Shell({ children }) {
return (
<ErrorBoundary FallbackComponent={Fallback} onError={logError}>
{children}
</ErrorBoundary>
);
}Errors passed through showBoundary are rethrown during render, so they also reach onError. One reporting hook covers both kinds, with one caveat. The component stack for a showBoundary error points at the component that called the hook, not at the code that raised the error. Keep the original error.stack as well.
Common problems
- The fallback shows, but "Try again" does nothing visible. The reset worked, but the same error was thrown again. Fix the cause, or clear the bad state in
onReset. - The boundary resets in a loop. An array or object inside
resetKeysis created on every render. Pass stable primitive values. showBoundaryhas no effect on a screen. The hook is called in a component that is outside the boundary, for example in the same component that renders<ErrorBoundary>. The boundary must be an ancestor of the caller.- The error appears twice in the console in development. React logs caught errors itself, and in development it may rethrow them for the browser's dev tools. This is not a bug in the boundary.
- A boundary inside the fallback throws. If the fallback itself throws, the error propagates to the next boundary up. Keep fallbacks simple.
Summary of the API
| Item | Purpose |
|---|---|
| `ErrorBoundary` | Class boundary with `fallback`, `FallbackComponent`, or `fallbackRender` |
| `resetErrorBoundary` | Passed to the fallback, clears the error and retries |
| `resetKeys` | Resets automatically when a value in the array changes |
| `onReset` | Runs on each reset so you can clear stale state |
| `onError` | Runs when a render error is caught, for logging |
| `useErrorBoundary` | Gives `showBoundary` and `resetBoundary` to descendants |
| `withErrorBoundary` | Wraps a component in a boundary at definition time |
Exercise
A ProductPage component renders <ErrorBoundary FallbackComponent={Fallback} resetKeys={[{ id: productId }]}>. Users report the fallback flashes and the page keeps re-rendering after an error. What is wrong, and how do you fix it?
Show answer
The resetKeys array contains a new object on every render, so Object.is sees a changed key each time and the boundary resets repeatedly. Pass a stable primitive instead: resetKeys={[productId]}.
Exercise
In a component inside an ErrorBoundary, an onClick handler calls await loadReport(), which sometimes rejects. The boundary's fallback never appears. What do you add to the component to send the failure to the boundary?
Show answer
Call const { showBoundary } = useErrorBoundary(); in the component, wrap the await in try/catch, and call showBoundary(error) in the catch block. The hook rethrows the error during render, which the boundary can catch.