← Lessons

quiz vs the machine

Gold1400

Frontend

React Error Boundaries

Catch render errors in a subtree and show a fallback instead of a blank page.

5 min read · core · beat Gold to climb

Why a blank screen happens

When a React component throws during rendering, React unmounts the whole tree by default, leaving a blank page. An error boundary stops that cascade by catching the error in a subtree and rendering a fallback.

An error boundary is a class component that implements one or both of these methods.

  • getDerivedStateFromError: receives the error and returns new state, used to flip to a fallback UI.
  • componentDidCatch: receives the error and component stack, used to log the failure.

What they do and do not catch

Boundaries catch errors during rendering, in lifecycle methods, and in constructors of the subtree below them.

They do not catch errors in event handlers, asynchronous code, or the boundary itself. Handle those with regular try catch or promise rejection handling.

Place several small boundaries so one broken widget does not blank a whole page.

Boundaries turn a catastrophic crash into a contained, recoverable failure.

Key idea

An error boundary catches render errors in its subtree and shows a fallback, but it does not catch event handler or async errors.

Check yourself

Answer to earn rating on the learn ladder.

1. What does an error boundary catch?

2. Which method is used to log a caught error and its component stack?

3. What does an error boundary NOT catch?