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
javascript
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
rust
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::{DecodeError, Engine}; pub fn encode_standard(data: &[u8]) -> String {
Base64 encode and decode in Rust
base64
encoding
error-handling
Beginner
7 steps
javascript
const FOCUSABLE = [ 'a[href]', 'button:not([disabled])', 'input:not([disabled])',
How to trap keyboard focus in a dialog
accessibility
dom
event-handling
Intermediate
8 steps
javascript
function generateCalendarGrid(year, month) { const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const daysInMonth = lastDay.getDate();
Building a text calendar in JavaScript
date-handling
grid-layout
modular-arithmetic
Intermediate
9 steps
rust
use std::collections::HashMap; #[derive(Debug)] pub struct RequestHead {
Parsing an HTTP request head in Rust
parsing
error-handling
iterators
Intermediate
9 steps
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
Intermediate
7 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.