A boundary keeps the rest of the page alive
React logs the caught error (with the component name), then calls componentDidCatch. Only the chart is replaced; the heading and the cart text stay.
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.
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.
A DeleteButton calls await api.delete(id) in its click handler. Make a failure show in the nearest error boundary.
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
What is an error boundary and how do you write one?
What's the difference between getDerivedStateFromError and componentDidCatch?
Which errors do error boundaries not catch, and how do you handle those?
How do you reset an error boundary? Compare a Try again button, reset keys and the key prop.
What are onCaughtError, onUncaughtError and onRecoverableError, and when would you use them?
Preview
Console
Nothing logged yet.Expected console output
TypeError: Cannot read properties of undefined (reading 'reduce')
The above error occurred in the <PriceChart> component.
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
componentDidCatch: Cannot read properties of undefined (reading 'reduce') | stack is a string
screen: Product page | Laptop, ₹55,000 | This widget failed to load. | Add to cart still works.