Skip to content

Error Boundaries

Catching render errors with error boundaries and showing fallback UI gracefully.

What you'll learn

  • What error boundaries are and why they are needed
  • Creating an error boundary class component
  • Showing fallback UI and logging errors
  • Limitations of error boundaries

Concept

The Problem Error Boundaries Solve

React components can throw errors during rendering, in lifecycle methods, or in constructors. Before error boundaries, an error in any component would unmount the entire React tree, showing a blank screen. This is a terrible user experience — one broken widget takes down the whole page. Error boundaries are React components that catch these errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.

Creating an Error Boundary

Error boundaries are currently class components only — there is no hook equivalent yet. A class component becomes an error boundary by implementing either getDerivedStateFromError() (to update state when an error is caught) or componentDidCatch() (to log the error). The getDerivedStateFromError method receives the error and returns a state update to trigger the fallback render. The componentDidCatch method receives the error and an info object with the component stack, useful for logging.

Using Error Boundaries

Wrap any part of your component tree in an error boundary. You can have multiple boundaries at different levels — a boundary around a specific widget isolates its errors from the rest of the page. The boundary's fallback UI can be anything: an error message, a retry button, or a skeleton placeholder. When the error is caught, only the subtree inside the boundary is replaced with the fallback; the rest of the app continues working.

Limitations

Error boundaries do not catch errors in event handlers, async code (setTimeout, requestAnimationFrame), or server-side rendering. For those, use try/catch blocks. Error boundaries only catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. Also, an error boundary cannot catch errors thrown by itself — only by its children.

Resetting Error State

Once an error boundary catches an error, it stays in the error state until the boundary re-renders. To reset it, you can change a key prop on the boundary (forcing a remount), provide a retry button that clears the error state, or use a route change to remount the boundary. This is important for user experience — users should be able to recover from errors without refreshing the page.

Example

              import React from "react";

// Error boundary — must be a class component.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  // Update state so the next render shows fallback UI.
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  // Log the error to an error reporting service.
  componentDidCatch(error, errorInfo) {
    console.error("Caught error:", error, errorInfo);
    // logErrorToService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong.</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage — wrap any component to isolate its errors.
function App() {
  return (
    <ErrorBoundary>
      <Header />
      <ErrorBoundary>
        <WidgetThatMightCrash />
      </ErrorBoundary>
      <Footer />
    </ErrorBoundary>
  );
}
            

ErrorBoundary catches errors in its children, shows a fallback with a retry button, and logs the error. Multiple boundaries isolate different parts of the UI.

Try it

  • Code Diff

    Compare error handling approaches when adding boundaries.

  • JSON Formatter

    Format error stack traces and component info for logging.

Common mistakes

The mistake

Expecting error boundaries to catch event handler errors

The fix

Error boundaries only catch errors during rendering, lifecycle methods, and constructors. For event handlers and async code, use try/catch. This is a React limitation, not a bug.

The mistake

Not providing a meaningful fallback UI

The fix

A blank fallback is as bad as a crash. Show a helpful message, a retry button, or contact information. Let users know what happened and what they can do about it.

Practice Error Boundaries

4 exercises

Practice Error Boundaries

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors