How to use React Error Boundaries to catch JavaScript errors

· Category: React

Short answer

Error Boundaries are React class components that implement static getDerivedStateFromError or componentDidCatch. They catch JavaScript errors in their child component tree and display a fallback UI.

Steps

  1. Create a class component with static getDerivedStateFromError() to update state.
  2. Optionally add componentDidCatch() to log errors to a monitoring service.
  3. Wrap parts of your app with the boundary.

Example

import { Component } from 'react';

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

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

  componentDidCatch(error, info) {
    console.error(error, info.componentStack);
  }

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

Tips

  • Error Boundaries do not catch errors in event handlers, async code, or server-side rendering.
  • For event handler errors, use standard try/catch blocks.
  • Tools like react-error-boundary provide a ready-made functional-component wrapper.