Sub topic 8
Letting users retry and reset
This chapter assumes you can write a class-based error boundary with getDerivedStateFromError and build a fallback UI. It also assumes you know that a boundary replaces its subtree once it catches an error.
Why a fallback is not enough
A boundary that has caught an error stays in its error state. The fallback keeps showing until the boundary unmounts or its state changes. If the failure was temporary, such as a dropped network request, the user can only reload the page and lose their place.
Recovery means clearing the boundary's error state so React tries to render the children again. If the children render successfully, the fallback disappears.
Resetting by clearing state
Add a reset method to the class boundary and pass it to the fallback:
import { Component } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
reset = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) {
return this.props.renderFallback({
error: this.state.error,
reset: this.reset,
});
}
return this.props.children;
}
}
function App() {
return (
<ErrorBoundary
renderFallback={({ error, reset }) => (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={reset}>Try again</button>
</div>
)}
>
<Profile />
</ErrorBoundary>
);
}reset is an arrow function property, so this stays bound when the fallback calls it as a click handler.
Retrying can fail again
Calling reset re-renders the children with the same props and state. If the cause is still there, the child throws again and the fallback returns immediately. The user sees a button that appears to do nothing.
Offer a retry only when the cause can change between attempts. A failed request can succeed on a second try. A bug caused by bad data will not. For permanent failures, give the user a different action, such as going back or contacting support.
Resetting by remounting with a key
React discards a component's state when its key changes and mounts a fresh instance. Putting a key on the boundary resets it, and also resets all of its children's state:
function Editor({ documentId }) {
return (
<ErrorBoundary key={documentId} renderFallback={renderFallback}>
<Document id={documentId} />
</ErrorBoundary>
);
}When the user opens a different document, documentId changes. The old boundary, which may be showing an error, is thrown away. A new one starts in the normal state. This is the simplest way to clear an error when the input that caused it has changed.
Resetting with react-error-boundary
The react-error-boundary library packages both patterns. It passes resetErrorBoundary to the fallback, and it clears the error automatically when any value in resetKeys changes. Unlike a key, a reset through resetKeys does not necessarily discard the state of the boundary's siblings or parents.
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 Editor({ documentId }) {
return (
<ErrorBoundary FallbackComponent={Fallback} resetKeys={[documentId]}>
<Document id={documentId} />
</ErrorBoundary>
);
}The library also accepts an onReset callback. Use it to clean up state outside the boundary, such as clearing a cache entry, before the children render again.
Choosing a reset method
| Method | Triggered by | Resets children's state? | Best for |
|---|---|---|---|
| `reset` button | User click | No, only the error | Transient failures such as network errors |
| `key` on the boundary | A changing prop | Yes, fully remounts | Switching to a different record or page |
| `resetKeys` | A changing value | No, only the error | Clearing the error when its input changes |
Exercise
A boundary wraps a component that fetches an order by orderId. The user sees the fallback after a failed fetch, then navigates to a different order. The fallback is still shown. Name two ways to fix this.
Show answer
Put key={orderId} on the boundary, so a new order mounts a fresh boundary in its normal state. Or, with react-error-boundary, pass resetKeys={[orderId]} so the error clears when orderId changes.