- React
- Advanced Component Design Patterns and Error Boundaries
- Error Boundaries: Declarative Exception Recovery
Error Boundaries: Declarative Exception Recovery
Error Boundaries are class components that catch JavaScript runtime errors during rendering, lifecycle methods, and constructors anywhere in their child tree, preventing full app crashes by displaying a fallback UI and logging exceptions to observability platforms.
Key Learning Objectives
Implement an Error Boundary using static getDerivedStateFromError and componentDidCatch.
Explain what errors Error Boundaries catch and what errors they CANNOT catch.
Build localized error boundaries to isolate failures in individual widgets without breaking the whole page.
Understand why Error Boundaries must still be class components in React 18/19.
The Interview Problem & Context
Implement a production Error Boundary component with error reset functionality, and explain why it does NOT catch errors in asynchronous code, event handlers, or SSR.
1import React, { Component, ErrorInfo, ReactNode } from 'react';23interface Props {4 fallback?: ReactNode;5 onReset?: () => void;6 children: ReactNode;7}89interface State {10 hasError: boolean;11 error: Error | null;12}1314export class ErrorBoundary extends Component<Props, State> {15 constructor(props: Props) {16 super(props);17 this.state = { hasError: false, error: null };18 }1920 // 1. Render fallback UI synchronously on next render21 static getDerivedStateFromError(error: Error): State {22 return { hasError: true, error };23 }2425 // 2. Log error & component stack to observability (e.g. Sentry, Datadog)26 componentDidCatch(error: Error, errorInfo: ErrorInfo) {27 console.error('ErrorBoundary captured exception:', error, errorInfo.componentStack);28 // reportToTelemetry(error, errorInfo);29 }3031 // 3. Recovery mechanism32 handleReset = () => {33 this.props.onReset?.();34 this.setState({ hasError: false, error: null });35 };3637 render() {38 if (this.state.hasError) {39 if (this.props.fallback) return this.props.fallback;40 return (41 <div role="alert" className="error-fallback">42 <h2>Something went wrong.</h2>43 <pre>{this.state.error?.message}</pre>44 <button onClick={this.handleReset}>Try Again</button>45 </div>46 );47 }48 return this.props.children;49 }50}
Deep Architectural Explanation
What Error Boundaries Catch vs What Escapes
Error Boundaries catch runtime exceptions during:
- Rendering phase (inside JSX or component functions).
- Lifecycle methods (
componentDidMount,useEffectrender phase). - Constructors of any child component in the subtree.
What Error Boundaries DO NOT Catch:
| Uncaught Error Category | Why it Escapes | How to Handle It |
|---|---|---|
Event Handlers (onClick) | Runs in browser event loop, NOT during React render | Traditional try / catch inside the callback |
Asynchronous Code (setTimeout, Promises) | Dispatched outside React's Fiber execution loop | .catch() handler or error state |
| Server-Side Rendering (SSR) | SSR uses string streaming, not Fiber mount loops | Server route error handling |
| Errors inside the Boundary itself | A boundary only catches errors from its children | Wrap boundary in a higher boundary |
Strategic Placement:
Wrap isolated UI sections (like a comments widget, sidebar, or chart) in separate boundaries. If the chart throws an error, only the chart displays a fallback—the navigation bar and rest of the dashboard remain fully interactive!
Common Interview Traps & Pitfalls
Expecting Error Boundary to catch network request failures or unhandled Promise rejections.
Wrapping only the root of the app in an error boundary, causing the entire screen to crash on a minor widget bug.
Forgetting to provide a reset mechanism so the user can retry after transient errors.
Senior Interviewer Follow-Up Probes
How does the popular `react-error-boundary` library implement `useErrorBoundary` reset triggers?
How do Error Boundaries interact with React 18 Suspense boundaries during concurrent rendering?
What happens to unhandled component errors in React 16+ if no Error Boundary is present in the tree?
Frequently Asked Interview Questions
Do Error Boundaries catch errors in event handlers like onClick?
No. Event handlers run outside the React render loop in browser event callbacks. Errors in event handlers do not corrupt the React tree; standard try/catch blocks must be used inside event handlers.
What is the difference between getDerivedStateFromError and componentDidCatch?
getDerivedStateFromError is called during the render phase and returns state to display the fallback UI synchronously. componentDidCatch is called in the commit phase and is used for side-effects like telemetry error logging.
What happens to the React tree if an unhandled render error occurs without a boundary?
React unmounts the entire component tree and displays a blank screen. React determined that leaving a corrupted, half-rendered UI on screen is dangerous and can cause data corruption.
Can you nest multiple Error Boundaries?
Yes. Granular error boundaries isolate subtrees. An error will bubble up to the closest enclosing ErrorBoundary, leaving outer components intact.
How do you reset an Error Boundary when route or props change?
Pass a reset key (e.g., location.pathname) or a key prop to the ErrorBoundary. Changing the key causes React to remount the boundary with initial clean state.
