React ยท Chapter 27 of 42

Error Boundaries

Error boundaries are components that catch JavaScript errors in their child component tree, log them, and display a fallback UI instead of crashing the whole app.

Error boundaries must currently be implemented as class components, using `static getDerivedStateFromError` and/or `componentDidCatch`.

Implementing one

Define a class with `static getDerivedStateFromError(error)` to update state, and `componentDidCatch(error, info)` to log details. Render a fallback when an error was caught.

Usage

Wrap parts of your tree that might fail (like a widget fetching data) with `<ErrorBoundary>{children}</ErrorBoundary>` to contain failures.

Example 1 (jsx)
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error(error, info);
  }
  render() {
    if (this.state.hasError) return <h2>Something went wrong.</h2>;
    return this.props.children;
  }
}
Output
Something went wrong. (shown if a child throws)

The boundary catches errors in children and renders a fallback UI.

Key points

  • Error boundaries catch rendering errors in their child tree.
  • They must currently be class components.
  • getDerivedStateFromError updates state to show a fallback UI.
  • componentDidCatch is used for logging error details.
๐Ÿ’ก Note: Error boundaries do not catch errors in event handlers, async code, or the boundary itself.

๐Ÿ“ Quick Quiz

1. Can error boundaries currently be function components?

2. What method updates state after catching an error?

3. What do error boundaries NOT catch?