Error Boundaries in React — How to Catch and Handle Errors
The Interview Question
What are error boundaries in React? What errors do they catch and what don't they catch?
Expert Answer
Error boundaries are React class components that catch JavaScript errors anywhere in their child component tree during rendering, lifecycle methods, and constructors. When an error is caught, they display a fallback UI instead of crashing the entire application. They work by implementing either or both of two lifecycle methods: getDerivedStateFromError (to render fallback UI) and componentDidCatch (to log error information). The critical limitation: error boundaries do NOT catch errors in event handlers, asynchronous code (setTimeout, fetch, promises), server-side rendering, or errors thrown in the error boundary itself. For event handler errors, you use regular try-catch. This is a common interview trap — candidates assume error boundaries catch everything.
Key Points to Hit in Your Answer
- Must be class components — no hook equivalent exists yet
- Catch errors during: rendering, lifecycle methods, constructors of child tree
- Do NOT catch: event handlers, async code, SSR, errors in the boundary itself
- Use getDerivedStateFromError for fallback UI, componentDidCatch for logging
- Place them strategically — wrap route-level components, not every div
- Libraries like react-error-boundary provide a hook-friendly wrapper
Code Example
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
// Log to your error tracking service
logErrorToService(error, errorInfo.componentStack);
}
render() {
if (this.state.hasError) {
return <FallbackUI error={this.state.error} />;
}
return this.props.children;
}
}
// Usage — wrap around route sections
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
What Interviewers Are Really Looking For
They want you to know the limitations as much as the capabilities. Calling out that async errors and event handlers aren't caught is crucial. Mentioning react-error-boundary as the community standard shows practical experience beyond textbook knowledge.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →