Course contentsShow
← React
Lesson 323 of 2,3969. Class Components (Legacy Overview)Free lesson

Error Boundaries: The Only Class-Exclusive Feature

Why error boundaries still require class components and how componentDidCatch/getDerivedStateFromError work.

Error Boundaries: The Only Class-Exclusive Feature

What you'll learn: Why error boundaries remain the one feature that must be implemented as class components, even in modern React.

The Exception to the Rule

You've learned how hooks replaced nearly every class component use case—state, lifecycle, refs, everything. But there's one holdout: error boundaries. As of now, React has no hook equivalent for catching rendering errors in child components.

Why Error Boundaries Need Classes

Error boundaries use two special lifecycle methods:

  • componentDidCatch(error, errorInfo) – Called after an error is thrown, lets you log error details or send to error tracking services
  • getDerivedStateFromError(error) – Called during render phase to update state and show a fallback UI

These methods tap into React's error-handling mechanism at a level hooks currently can't reach. They catch errors in:

  • Child component rendering
  • Lifecycle methods
  • Constructors of the component tree below

The Pattern in Practice

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state to show fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log error to service
    console.error('Error caught:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

You wrap parts of your tree in this class component, even if everything else uses hooks.

Key Takeaway: Error boundaries are the only feature still requiring class components—you'll write or import one class-based error boundary, then use function components everywhere else in modern React apps.