Error Boundaries

An uncaught error during rendering unmounts the entire root: React 7,897 would rather show nothing than a corrupted interface. An error boundary catches errors thrown by its subtree while rendering and shows a fallback instead. It is the only React feature that still requires a class, because there is no Hook equivalent of static getDerivedStateFromError.

A boundary that catches a child which throwsJavaScript
class ErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }  // choose the fallback
  componentDidCatch(error, info) { log(error, info.componentStack); }  // report it
  render() {
    const e = this.state.error;
    return e ? <p className="fb">Chart failed: {e.message}</p> : this.props.children;
  }
}
const Chart = () => { throw new Error('series is empty'); };
const Dashboard = () => (        // only the chart is replaced by the red fallback
  <div>
    <h3>Sales</h3>
    <ErrorBoundary><Chart /></ErrorBoundary>
    <p>The rest of the dashboard renders normally.</p>
  </div>
);

getDerivedStateFromError runs during rendering and must be pure; componentDidCatch runs afterwards and is where side effects belong, such as logging to Sentry 92 . React 19 produces a single console entry per error, where earlier versions logged the same one up to three times.

Boundaries do not catch errors in event handlers, in setTimeout or promise callbacks, during server rendering, or thrown by the boundary itself — those are ordinary JavaScript errors, so use try/catch. What a boundary does catch, it catches for everything below it, so placement matters: one per route stops a broken widget blanking the application, one per panel keeps a failure local. Reset a boundary by giving it a new key, which remounts the subtree.

For production, use react-error-boundary 7,993 (https://github.com/bvaughn/react-error-boundary 7,993 ) (6.1.5, MIT, npm 2,036 i react-error-boundary). It wraps the class and adds what you would otherwise write yourself: FallbackComponent receives a resetErrorBoundary function, resetKeys retries when a dependency changes, onError and onReset hook into logging, and useErrorBoundary returns showBoundary so an async failure can be pushed into the nearest boundary. At the root, createRoot takes onUncaughtError and onCaughtError callbacks that route what React catches into your logger.