Skip to main content

Overview

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
Error boundaries do not catch errors for:
  • Event handlers
  • Asynchronous code (e.g., setTimeout or requestAnimationFrame callbacks)
  • Server-side rendering
  • Errors thrown in the error boundary itself (rather than its children)

Creating an Error Boundary

A class component becomes an error boundary if it defines static getDerivedStateFromError() or componentDidCatch() lifecycle methods.

Basic Error Boundary

Lifecycle Methods

getDerivedStateFromError

This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown and should return a value to update state. Called during the render phase, so side-effects are not permitted.

componentDidCatch

This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:
  1. error - The error that was thrown
  2. errorInfo - An object with a componentStack property containing stack trace information
Called during the commit phase, so side-effects are permitted. Use it for logging errors.

Advanced Error Boundary

Usage Patterns

Wrapping Top-Level Routes

Multiple Error Boundaries

Custom Fallback UI

Error Boundaries with Async Data

Error Boundaries vs Try-Catch

Error boundaries only catch errors in React components. For event handlers, use try-catch:

Logging Errors

Integrate with error monitoring services:

Error Boundaries in Development vs Production

Best Practices

  1. Use multiple error boundaries: Don’t wrap your entire app in one boundary
  2. Provide recovery mechanisms: Include “Try Again” or “Reload” buttons
  3. Log errors properly: Always log to monitoring services in production
  4. Show user-friendly messages: Don’t expose technical details in production
  5. Reset error boundaries: Use keys to reset boundaries when needed
  6. Handle async errors: Use try-catch for promises and async operations
  7. Test error scenarios: Explicitly test that error boundaries work

Granular Error Boundaries

Limitations

Error boundaries have several limitations:
  1. Only class components: Error boundaries must be class components (no hook equivalent yet)
  2. Render errors only: Don’t catch errors in event handlers or async code
  3. No self-catching: Can’t catch errors thrown in the boundary itself
  4. No SSR errors: Don’t catch errors during server-side rendering

See Also