Advanced
Error boundaries
Catching render errors and showing fallback UI without crashing the app.
An error boundary is a component that catches JavaScript errors in its child tree during render, in lifecycle methods, and in constructors, then renders a fallback UI instead of unmounting the whole app.
An error boundary is a circuit breaker: when one appliance shorts, it trips only that circuit instead of blacking out the whole house.
Key concepts
1
They are implemented with class components using static getDerivedStateFromError (render the fallback) and componentDidCatch (log to your monitoring service). Function components use a library wrapper (react-error-boundary).
static getDerivedStateFromErrorcomponentDidCatchreact-error-boundary
2
Boundaries do not catch errors in event handlers, async code, or SSR — handle those with try/catch. Place boundaries strategically (per route, per widget) so one broken panel does not blank the page.
not
3
Pitfall: a single top-level boundary means any error blanks everything; granular boundaries isolate failures. Interview angle: "what can’t an error boundary catch?" — event handlers and async errors.
Pitfall:Interview angle:
jsx
class Boundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) { return { error }; }
componentDidCatch(error, info) { logToSentry(error, info); }
render() {
return this.state.error ? <Fallback onRetry={() => this.setState({ error: null })} /> : this.props.children;
}
}
// <Boundary><Dashboard /></Boundary>