Sub topic 8
Letting users retry and reset
This chapter assumes you can write a class-based error boundary with getDerivedStateFromError, and that you know where boundaries do and don't catch errors. It also assumes you have used React state and useEffect. Here you will learn how a boundary leaves its failed state, and how to offer retries without creating loops or hiding the real cause.
Why a boundary stays failed
A boundary from the earlier chapters stores the error in state. Once state.error is set, render returns the fallback on every render. Nothing in React clears that state for you.
This matters because many failures are temporary: a dropped network request, a record that was being saved, a bad value the user has since fixed. Without a reset path, the only recovery is a full page reload, which throws away everything else the user had on screen.
A reset does one thing: it clears the boundary's error state so the boundary renders its children again. Those children mount fresh, because they were unmounted when the fallback appeared. A reset does not fix the cause. If the same code throws again, the boundary catches it again.
Adding a reset method to a class boundary
The smallest change is a method that sets the error back to null. Passing it to the fallback lets the fallback render a button.
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>Could not load the profile: {error.message}</p>
<button onClick={reset}>Try again</button>
</div>
)}
>
<Profile />
</ErrorBoundary>
);
}reset is an arrow function assigned as a class field, so it keeps its this when passed as a callback. A regular method would lose this when handed to onClick.
Resetting by remounting with a key
Sometimes you don't need a reset button at all. A different key on a component makes React discard the old instance and create a new one, including its state. If you put the key on the boundary, a new key means a new boundary with error: null.
function ProfilePage({ userId }) {
return (
<ErrorBoundary key={userId} renderFallback={Fallback}>
<Profile userId={userId} />
</ErrorBoundary>
);
}If user 7's profile throws and the user navigates to user 8, the boundary resets. This is simple and needs no extra code. The cost is that everything under the key loses its state, because it all remounts. Use it when a full remount is acceptable, such as a page or a route.
Resetting automatically when inputs change
A more precise tool is a list of reset keys. When any value in the list changes while the boundary is showing an error, the boundary resets itself. Unlike key, the boundary itself stays mounted, and nothing resets while it is healthy.
Here is how to build that in a class boundary.
import { Component } from "react";
function changed(a = [], b = []) {
return (
a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))
);
}
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidUpdate(prevProps, prevState) {
const hadErrorBefore = prevState.error !== null;
if (
this.state.error !== null &&
hadErrorBefore &&
changed(prevProps.resetKeys, this.props.resetKeys)
) {
this.reset();
}
}
reset = () => {
this.props.onReset?.();
this.setState({ error: null });
};
render() {
if (this.state.error) {
return this.props.renderFallback({
error: this.state.error,
reset: this.reset,
});
}
return this.props.children;
}
}The hadErrorBefore check is the important detail. Suppose the same update that changes resetKeys also causes the child to throw. The boundary then has an error, but that error was caused by the new keys. If the boundary reset immediately, it would render the children again, hit the same error, and loop. By requiring that the error was already present in the previous state, the boundary resets only when the keys change after a failure was shown.
Using react-error-boundary
The react-error-boundary library implements all of this. It supplies resetErrorBoundary to the fallback, a resetKeys prop, and an onReset callback that runs before the children render again. Use onReset to clear anything outside the boundary that caused the failure.
import { useRef } from "react";
import { ErrorBoundary } from "react-error-boundary";
function Editor({ documentId }) {
const attempts = useRef(0);
return (
<ErrorBoundary
resetKeys={[documentId]}
onReset={(details) => {
attempts.current =
details.reason === "keys" ? 0 : attempts.current + 1;
}}
fallbackRender={({ error, resetErrorBoundary }) =>
attempts.current >= 3 ? (
<div role="alert">
<p>This keeps failing: {error.message}</p>
<button onClick={() => window.location.reload()}>
Reload the page
</button>
</div>
) : (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}
>
<Document id={documentId} />
</ErrorBoundary>
);
}Three behaviors are worth noticing here:
resetKeys={[documentId]}resets the boundary when the user opens a different document. The array can be a new array on every render, because the library compares its items one by one.onResetreceives details. In recent versions,details.reasonis"keys"when a key changed and"imperative-api"whenresetErrorBoundarywas called. The code above counts only manual retries and starts over when the document changes.- The retry counter lives in a
useRefin the parent, not in the fallback. The fallback unmounts on every reset, so any state inside it would be lost.
Clearing the cause before retrying
A retry can only succeed if something is different the second time. Rendering the same component with the same data produces the same error. Check what the failing component depends on:
| Cause of the error | What a plain reset does | What you need to add |
|---|---|---|
| Transient fetch failure, with no caching | The component fetches again and may succeed | Nothing extra |
| Fetch failure stored in a cache | The cached failure is read again and thrown again | Clear or invalidate that cache entry in `onReset` |
| Bad data in parent state | The same data is rendered again | Fix or discard the data in `onReset` |
| Bug in the component's code | It throws again | A code fix. Offer a reload or a link to support instead of an endless retry |
| Failed lazy import | Often retries the import. Some bundlers or browsers cache the failure | A page reload may be the only reliable recovery |
If the cache and the boundary are not coordinated, the "Try again" button appears to do nothing. The user clicks, the fallback flickers, and the same message returns. That experience is worse than having no button.
Choosing a reset strategy
| Strategy | Triggered by | State lost | Best for |
|---|---|---|---|
| Reset method or `resetErrorBoundary` | User click | Only the failed subtree (it was already unmounted) | Transient failures with a clear retry action |
| `key` on the boundary | A changed identifier | The boundary and everything in it, even when healthy | Route or page level, one boundary per entity |
| `resetKeys` | A changed input while failed | Only the failed subtree | Recovering when the user changes the input that caused the error |
| Page reload | User click | All client state | Repeated failures, failed code loading |
These can be combined. A common setup uses resetKeys for inputs, a retry button for transient errors, and a reload button after a few failed attempts.
Pitfalls
- Retry loops. A boundary that resets automatically, for example on a timer, can re-render a failing component forever. Cap automatic attempts, and prefer user-triggered retries.
- Unstable reset keys. An item such as
{ id }created inline is a new object each render, soObject.issees a change every time. Put primitive values inresetKeys, such as ids and strings. - Resetting without cleaning up. Side effects from the failed attempt, such as subscriptions, timers, or partial writes, may need cleanup in
onReset. - Fallbacks that throw. A boundary does not catch errors thrown by its own fallback. The error moves up to the next boundary above, so keep the fallback simple and make sure a boundary exists higher in the tree.
- Focus and accessibility. The fallback replaces the part of the page the user was interacting with, so keyboard focus may be lost. Use
role="alert"so assistive technology announces the message, and consider moving focus to the retry button.
Exercises
Exercise
A boundary shows a fallback after Profile throws because the user's session expired. The user logs in again in another tab and clicks "Try again". The same error appears. List two reasons this could happen, and one fix for each.
Show answer
First, the failed result may be cached outside React, for example a rejected request stored in a data cache, so the retry reads the same rejection. Fix: invalidate that cache entry in onReset. Second, the app's session or auth state may not have updated in this tab, so the retried request is still sent with the old session. Fix: refresh the session state in onReset before the children render again. In both cases the reset itself works. What is missing is a change in the thing the child depends on.
Exercise
You wrap each article page in <ErrorBoundary resetKeys={[article]}>, where article is an object loaded from the server and replaced on each render by a new object with the same contents. After one failure, the boundary seems to reset itself repeatedly. Why, and how do you fix it?
Show answer
resetKeys compares items with Object.is. A new object on every render never equals the previous one, so the boundary sees a changed key after each update and resets, which renders the children, which fail again. Use a stable primitive instead, such as resetKeys={[article.id]}.