React Dojo

Search

Search concepts, exercises and quizzes

API · Error handling

Error Boundary

Isolate errors so they don't bring down the entire UI

Without an Error Boundary, an error in any child component destroys the entire tree and the user sees a blank screen. An Error Boundary intercepts the error, displays a fallback UI, and leaves the rest of the application intact.

Why do they exist?

React propagates render errors upward until something catches them. If nothing does, the entire tree unmounts. An Error Boundary acts like a try/catch for the component tree: it catches the error, updates its own state to show a fallback, and leaves the rest of the app untouched. It's the foundation of graceful degradation in React.

How to build one

It must be a class — there's no native functional equivalent. It needs two lifecycle methods:

  • static getDerivedStateFromError(error) — a static, pure method that returns the new state. React calls it during the render phase to display the fallback.
  • componentDidCatch(error, info) — runs after render. This is where side effects go: logs, sending data to a monitoring service (Sentry, Datadog…).

Use it just like <Suspense>: wrap the subtree you want to protect.

What it catches and what it doesn't

✅ Catches errors in render, lifecycle methods, and child component constructors.

❌ Does not catch:

  • Event handlers — events don't go through React's render cycle. Use try/catch inside the handler.
  • Async codesetTimeout, fetch, promises. The error occurs outside the React tree.
  • Server-side rendering (SSR).
  • Its own errors — an Error Boundary can't catch its own errors. You need another Error Boundary parent to wrap it.

Common pitfalls

  • 01Event handlers don't propagate errors to the React tree — use try/catch inside the handler, not an Error Boundary.
  • 02An Error Boundary can't catch its own errors — you need another Error Boundary parent wrapping it.
  • 03In development with StrictMode, React intentionally re-throws the error after catching it. In production the behavior is as expected.
  • 04A retry button that only resets hasError won't help if the child still throws. Pass a key that changes when you want React to fully unmount and remount the boundary from scratch.
Was this helpful?
Sign in to give feedback