QuestionsReact

Error boundaries

ResilienceMediumReact

What is an error boundary, what does it catch and not catch, and how do you use one?

What it tests

Knowing React's failure model and how to contain render-time crashes.

Approach & answer

An error boundary is a component that catches JavaScript errors thrown during rendering, in lifecycle methods, and in constructors of the tree BELOW it — then renders a fallback UI instead of letting the whole app unmount to a blank screen. It must be a class component implementing static getDerivedStateFromError (to flip to the fallback) and/or componentDidCatch (to log to a service). Crucially, it does NOT catch: errors in event handlers (use try/catch there — those aren't during render), asynchronous code (setTimeout, fetch callbacks), server-side rendering, or errors thrown in the boundary itself. Place boundaries strategically — one near the root for a global fallback, plus finer-grained boundaries around independent regions (a widget, a route, a dashboard panel) so one failing section doesn't take down the rest. There is no built-in hook version; teams use react-error-boundary, which also adds a reset mechanism to recover without a full reload. Pair boundaries with Suspense for a complete loading-and-error story.

Use this technique when

Wrapping routes, widgets, or third-party/render-risky subtrees so a crash degrades locally instead of blanking the app.

References

jsx