React Curriculum

Error Boundaries: Declarative Exception Recovery

Medium100% Free~25 mins#react#patterns#error-boundaries#resilience#lifecycle#production
Interview Answer (30-Second Summary)

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';
2
3interface Props {
4 fallback?: ReactNode;
5 onReset?: () => void;
6 children: ReactNode;
7}
8
9interface State {
10 hasError: boolean;
11 error: Error | null;
12}
13
14export class ErrorBoundary extends Component<Props, State> {
15 constructor(props: Props) {
16 super(props);
17 this.state = { hasError: false, error: null };
18 }
19
20 // 1. Render fallback UI synchronously on next render
21 static getDerivedStateFromError(error: Error): State {
22 return { hasError: true, error };
23 }
24
25 // 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 }
30
31 // 3. Recovery mechanism
32 handleReset = () => {
33 this.props.onReset?.();
34 this.setState({ hasError: false, error: null });
35 };
36
37 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:

  1. Rendering phase (inside JSX or component functions).
  2. Lifecycle methods (componentDidMount, useEffect render phase).
  3. Constructors of any child component in the subtree.

What Error Boundaries DO NOT Catch:

Uncaught Error CategoryWhy it EscapesHow to Handle It
Event Handlers (onClick)Runs in browser event loop, NOT during React renderTraditional 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 loopsServer route error handling
Errors inside the Boundary itselfA boundary only catches errors from its childrenWrap 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
Why must Error Boundaries be class components in React?

React has not introduced functional hook equivalents for static getDerivedStateFromError or componentDidCatch. The React team stated that error handling requires fiber-level catches that fit class lifecycle semantics.

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.

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.

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.

Yes. Granular error boundaries isolate subtrees. An error will bubble up to the closest enclosing ErrorBoundary, leaving outer components intact.

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.