React Error Boundaries: Graceful Error Handling

Error boundaries catch JavaScript errors in component trees and display fallback UI instead of crashing your whole app.

Creating an Error Boundary

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };
  
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  
  componentDidCatch(error, errorInfo) {
    // Log to error reporting service
    logErrorToService(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong.</h2>
          <button onClick={() => window.location.reload()}>
            Reload page
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

Usage

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Limitations

  • Only class components can be error boundaries
  • Don’t catch errors in event handlers (use try/catch)
  • Don’t catch errors in async code
  • Don’t catch errors in SSR

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.