React Error Boundaries: Graceful Error Handling

On this page

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

Creating an Error Boundary

JSX26 lines
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

JSX3 lines
<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.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

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.