stackademic

The leading education platform for anyone with an interest in software development.

React Error Boundaries

Catch render errors in a subtree and show a fallback UI

Overview

An error boundary is a component that catches JavaScript errors thrown during rendering, in lifecycle methods, and in constructors of its children. It renders a fallback UI instead of crashing the whole app. Error boundaries must be class components, but you consume them from functional components normally.

Syntax / Usage

Implement getDerivedStateFromError to update state and componentDidCatch to log the error.

import { Component } from 'react'

class ErrorBoundary extends Component {
  state = { hasError: false }

  static getDerivedStateFromError() {
    return { hasError: true }
  }

  componentDidCatch(error, info) {
    console.error('Caught by boundary:', error, info.componentStack)
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? <p>Something went wrong.</p>
    }
    return this.props.children
  }
}

Examples

Wrap a feature so a crash is isolated to that section:

function Dashboard() {
  return (
    <ErrorBoundary fallback={<p>Widget failed to load.</p>}>
      <RevenueWidget />
    </ErrorBoundary>
  )
}

Reset the boundary with a key so users can retry after navigation changes:

function Page({ route }) {
  return (
    <ErrorBoundary key={route}>
      <RouteContent route={route} />
    </ErrorBoundary>
  )
}

For a functional API, most teams use react-error-boundary, which adds reset handlers and a useErrorBoundary hook on top of the same mechanism.

Common Mistakes

  • Expecting boundaries to catch errors in event handlers—wrap those in try/catch instead
  • Trying to catch errors in async code or setTimeout callbacks, which boundaries don't intercept
  • Placing a single boundary at the root so any error blanks the entire page
  • Forgetting that boundaries don't catch errors thrown in their own render, only in children
  • Not logging componentDidCatch info, losing valuable component stack traces

See Also

components react-suspense react-custom-hooks