An error boundary is a component that catches JavaScript errors thrown while rendering its children (and in their lifecycle methods and constructors), renders a fallback UI instead of letting the whole app unmount, and can log the error. Since React 16, an uncaught render error unmounts the entire root, so boundaries are how you contain failures. They are still class components only (static getDerivedStateFromError + componentDidCatch). There's no hook, even in React 19, so most teams use react-error-boundary.
class ErrorBoundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error }; // render phase: switch to fallback
}
componentDidCatch(error, info) {
reportError(error, info.componentStack); // commit phase: side effects OK
}
render() {
if (this.state.error) {
return this.props.fallback ?? <p role="alert">Something went wrong.</p>;
}
return this.props.children;
}
}
<ErrorBoundary fallback={<WidgetError />}>
<RevenueChart />
</ErrorBoundary>
try/catch, then set state so the error shows in UI).setTimeout, promise callbacks, fetch().then, unless you rethrow it into render (e.g. setState(() => { throw err; }), or via use(promise)/Suspense data sources).React 19 also lets errors thrown in Actions (useActionState, <form action>, startTransition with async functions) propagate to the nearest error boundary.
Place boundaries like bulkheads:
Too few means a small bug blanks the app. Too many means fragmented, inconsistent error UI.
Boundaries stay in the error state until reset. Common approaches:
react-error-boundary's resetErrorBoundary and resetKeys (reset when, say, the route or a query key changes).key to remount it.QueryErrorResetBoundary).console.error), instead of being rethrown and logged twice.createRoot/hydrateRoot take onCaughtError (caught by a boundary), onUncaughtError (not caught, so the app unmounts) and onRecoverableError (React recovered automatically, e.g. a hydration mismatch). This is the right place to wire up monitoring such as Sentry.fetch in useEffect. It won't unless you surface the error during render.role="alert" and a clear recovery action.react-error-boundary with resets.Spotted a mistake or a rights concern? Report an issue