Sub topic 9
Using react-error-boundary with function components
This chapter assumes you can write function components with hooks, and that you know how a class-based boundary works from the earlier chapters. You should also be comfortable with try/catch and async/await.
Why use a library
React still requires a class component to catch rendering errors. There is no hook for it. The react-error-boundary package wraps that class for you, so a function-component codebase doesn't need to contain one. It also adds three things you would otherwise build yourself: a reset mechanism, automatic reset when data changes, and a hook for sending event handler and async errors to a boundary.
Install it with npm install react-error-boundary.
The ErrorBoundary component
ErrorBoundary takes the place of the hand-written class. You choose one of three ways to describe the fallback:
| Prop | What you pass | Use it when |
|---|---|---|
| `fallback` | A React element | The message is static and needs no error details |
| `FallbackComponent` | A component | The fallback needs the error or a reset button |
| `fallbackRender` | A function returning JSX | You want an inline fallback that reads the error |
A fallback component receives two props: error, the thrown value, and resetErrorBoundary, a function that clears the error state and renders the children again.
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 Profile({ userId }) {
return <p>Profile for user {userId}</p>;
}
function App() {
return (
<ErrorBoundary FallbackComponent={Fallback}>
<Profile userId={1} />
</ErrorBoundary>
);
}Clicking "Try again" re-renders Profile. If the cause is still there, the error is thrown again and the fallback returns. For that reason, a bare retry button works best for transient failures such as a flaky network.
Resetting automatically with resetKeys
Often the error depends on some input, such as a document ID. Once the input changes, the old error no longer applies. The resetKeys prop takes an array of values. When any value differs from the previous render, the boundary resets itself.
function Editor({ documentId }) {
return (
<ErrorBoundary FallbackComponent={Fallback} resetKeys={[documentId]}>
<Document id={documentId} />
</ErrorBoundary>
);
}If the user navigates from a broken document to another one, the fallback disappears without any click. The onReset prop runs when a reset happens, whether by button or by resetKeys. Use it to clear cached state that may have caused the error.
Sending handler and async errors to the boundary
Boundaries only catch errors thrown during rendering. The useErrorBoundary hook gives you showBoundary, which hands any error to the nearest boundary above the calling component.
import { useErrorBoundary } from "react-error-boundary";
function SaveButton() {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}The hook also returns resetBoundary, which does the same as resetErrorBoundary for code inside the boundary's children.
Reporting errors
The onError prop runs when the boundary catches an error. It receives the error and an info object with componentStack, the same data componentDidCatch gives you.
function logError(error, info) {
console.error(error, info.componentStack);
}
<ErrorBoundary FallbackComponent={Fallback} onError={logError}>
<Profile userId={1} />
</ErrorBoundary>Replace console.error with a call to your logging service.
Common mistakes
- Putting
resetKeysvalues that change on every render, such as a new array or object each time. The boundary then resets constantly and the fallback flashes. - Calling
showBoundaryfrom a component that is outside the boundary. The hook finds the nearest boundary above it, and throws if none exists. - Expecting the library to catch errors in its own fallback. A fallback that throws passes the error to the next boundary up.
Exercise
A user opens document 3, which throws while rendering. The Editor uses <ErrorBoundary FallbackComponent={Fallback} resetKeys={[documentId]}>. The user then picks document 4 from a sidebar that sits outside the boundary. What happens, and why?
Show answer
The boundary resets and renders document 4. The documentId value in resetKeys changed from 3 to 4, which clears the stored error. The fallback goes away without a click. The sidebar is outside the boundary, so it stayed working the whole time.