React cookbook · Beginner
Handle errors gracefully with error boundaries
Show a friendly fallback with a retry button when part of the UI crashes or fails to load data.
Approach
Wrap independent sections in react-error-boundary's ErrorBoundary so one failure doesn't blank the whole page. Report errors to your monitoring tool in onError, and reset the boundary (and TanStack Query errors) on retry.
Solution
import { ErrorBoundary, type FallbackProps } from "react-error-boundary";
import { QueryErrorResetBoundary } from "@tanstack/react-query";
function SectionError({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert" className="error-card">
<p>Something went wrong loading this section.</p>
{import.meta.env.DEV && <pre>{error instanceof Error ? error.message : String(error)}</pre>}
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export function Section({ children }: { children: React.ReactNode }) {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
FallbackComponent={SectionError}
onReset={reset}
onError={(error, info) => reportError(error, { componentStack: info.componentStack })}
>
{children}
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
);
}
Pitfalls
- One boundary at the root only.
- Expecting boundaries to catch event handler errors (use try/catch there).
- Showing stack traces to users in production.
Variations
- React Router
errorElementfor route-level errors. - Use
useSuspenseQuery+throwOnErrorto route data errors to boundaries.
Further reading: react-error-boundary
Reference: https://github.com/bvaughn/react-error-boundary