Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.5 — Error Boundaries
React · Example 3 of 4

A react-error-boundary style boundary with reset

Picking product 2 resets the boundary through resetKeys. Try again calls onReset (back to product 1, which works) before clearing the error, so the reset doesn't throw again.

An error boundary is a class component with static getDerivedStateFromError (show a fallback) and componentDidCatch (log), that catches errors thrown while rendering its children; it doesn't catch errors in event handlers or async code, it's reset with a key or a reset function, and React 19 adds root-level onCaughtError, onUncaughtError and onRecoverableError callbacks.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a reusable ErrorBoundary that takes a fallback render function (error, reset) => JSX and use it around a component that throws when a prop is negative.

02

A DeleteButton calls await api.delete(id) in its click handler. Make a failure show in the nearest error boundary.

03

Configure createRoot so that caught errors are logged with console.warn and uncaught ones with console.error, each with the component stack.

Explain it without notes

01

What is an error boundary and how do you write one?

02

What's the difference between getDerivedStateFromError and componentDidCatch?

03

Which errors do error boundaries not catch, and how do you handle those?

04

How do you reset an error boundary? Compare a Try again button, reset keys and the key prop.

05

What are onCaughtError, onUncaughtError and onRecoverableError, and when would you use them?

A react-error-boundary style boundary with reset

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

logged: No product 3
click 3: Something went wrong: No product 3
click 2: Product 2: Phone
logged: No product 3
click 3: Something went wrong: No product 3
try again: Product 1: Laptop