Home / Learn React / Error Boundaries

Error Boundaries

If one component crashes while rendering, you do not want the whole page to go blank. An error boundary catches the error and shows a safe message for that part.

In shortWrap a risky part in an error boundary. The simplest way is the react-error-boundary library, or write one class component.

Theory in plain words

The boundary protects the restHeaderWidget(crashes)ErrorBoundaryFooterApp
The boundary protects the rest

What it is

An error boundary is a component that catches JavaScript errors thrown while rendering its children, and shows a fallback UI instead of crashing the whole tree.

Why we use it

Since React 16, an uncaught render error unmounts the entire app, leaving a blank white page. Boundaries keep the rest of the page alive and give you a place to log the error.

How it works

A class with static getDerivedStateFromError(error) returns new state that triggers the fallback. componentDidCatch(error, info) logs it. Boundaries do not catch errors in event handlers, async code or the boundary itself.

Where it is used

  • Around widgets, routes and third party components
  • Reporting errors to Sentry or a log
  • A "Try again" button that resets the section
A class error boundaryTry it Yourself

What boundaries do not catch

The react-error-boundary library
npm install react-error-boundary

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary FallbackComponent={Oops} onReset={() => refetch()}>
  <Dashboard />
</ErrorBoundary>
Tip:React 19 adds root options onCaughtError, onUncaughtError and onRecoverableError to createRoot so you can log all errors in one place.

Quick quiz

1. What does an error boundary catch?

2. How do you write an error boundary yourself?

3. Where do you handle errors inside onClick?

Common questions

What does an error boundary catch?

Errors while rendering its children. Render, lifecycle and constructor errors of the tree below.

How do you write an error boundary yourself?

A class with getDerivedStateFromError. Boundaries still need a class (or the react-error-boundary library).

Where do you handle errors inside onClick?

try / catch in the handler. Boundaries do not catch event handler errors.