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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Error boundaries must be class components because they rely on lifecycle hooks React doesn't expose to hooks.
- 2Separate concerns: getDerivedStateFromError updates UI state while componentDidCatch handles side effects like logging.
- 3Accepting a function fallback and a resetKey turns a boundary into a reusable, recoverable component.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-react-errorboundary-works-explained-javascript-cd76/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.