Sub topic 3
Letting Users Retry and Reset
Assume you know function components, props, state, lifecycle methods, and async/await. An error boundary can show fallback UI, but recovery requires resetting the failed subtree and any state that caused the failure.
Retry with `react-error-boundary`
The react-error-boundary library provides a function-component-friendly boundary. Its fallback receives the error and a resetErrorBoundary function. Changing resetKeys also resets the boundary.
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Could not load the document: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function SaveButton() {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await saveDocument();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}
export function Editor({ documentId }) {
return (
<ErrorBoundary
FallbackComponent={Fallback}
resetKeys={[documentId]}
onError={(error, info) => reportError(error, info.componentStack)}
>
<SaveButton />
</ErrorBoundary>
);
}showBoundary routes an event-handler or asynchronous error to the nearest boundary. A reset should also clear or change the bad input, request, or identifier. Otherwise, the same error may immediately return.
Report component stacks
The info.componentStack value identifies the React components involved. Send it with the error, route, user-safe context, and a request identifier. Avoid putting secrets or personal data in logs.
Lazy components and Suspense
Suspense handles loading. The error boundary handles a failed dynamic import.
<ErrorBoundary fallback={<p>The chart failed to load.</p>}>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
</ErrorBoundary>Root-level error callbacks
React 19 supports centralized callbacks when creating a root:
const root = createRoot(document.getElementById("root"), {
onCaughtError: (error, info) =>
reportError("caught", error, info.componentStack),
onUncaughtError: (error, info) =>
reportError("uncaught", error, info.componentStack),
});Use these for consistent reporting. Boundaries still control local recovery UI.
Test the fallback
Trigger a rendering error with a test-only component and assert that the fallback appears and its retry button works.
function Broken() {
throw new Error("broken");
}
test("shows and resets the fallback", async () => {
const user = userEvent.setup();
render(
<ErrorBoundary FallbackComponent={Fallback}>
<Broken />
</ErrorBoundary>
);
expect(screen.getByRole("alert")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /try again/i }));
});Exercise
Why should a retry change state, props, or external conditions rather than only dismiss the fallback?
Show answer
Without changing the cause of the error, rendering repeats the same failure and the fallback returns.