javascript 49 lines · 8 steps

How a React ErrorBoundary works

A class component that catches render errors, reports them, and shows recoverable fallback UI.

Explained by highlit
1import { Component } from 'react';
2import { reportError } from './services/telemetry';
3 
4export class ErrorBoundary extends Component {
5 state = { error: null };
6 
7 static getDerivedStateFromError(error) {
8 return { error };
9 }
10 
11 componentDidCatch(error, info) {
12 reportError(error, {
13 componentStack: info.componentStack,
14 boundary: this.props.name ?? 'unnamed',
15 });
16 }
17 
18 componentDidUpdate(prevProps) {
19 if (this.state.error && prevProps.resetKey !== this.props.resetKey) {
20 this.setState({ error: null });
21 }
22 }
23 
24 handleRetry = () => this.setState({ error: null });
25 
26 render() {
27 const { error } = this.state;
28 
29 if (error) {
30 if (typeof this.props.fallback === 'function') {
31 return this.props.fallback({ error, retry: this.handleRetry });
32 }
33 
34 return (
35 this.props.fallback ?? (
36 <div role="alert" className="error-boundary">
37 <h2>Something went wrong</h2>
38 <p>{error.message}</p>
39 <button type="button" onClick={this.handleRetry}>
40 Try again
41 </button>
42 </div>
43 )
44 );
45 }
46 
47 return this.props.children;
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Error boundaries must be class components because they rely on lifecycle hooks React doesn't expose to hooks.
  2. 2Separate concerns: getDerivedStateFromError updates UI state while componentDidCatch handles side effects like logging.
  3. 3Accepting a function fallback and a resetKey turns a boundary into a reusable, recoverable component.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a React ErrorBoundary works — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code