Frontend Patterns

Pattern

Error Boundary

Catch JavaScript errors in component trees and display fallback UI gracefully.

Performance Advanced

Error Boundary

Problem

Uncaught JavaScript errors crash the entire application, leaving users with a blank white screen and no explanation. A single broken component can take down an entire page, even when 95% of the functionality is working fine, with no way to recover or show a helpful error message.

Solution

Catch component errors during rendering and display fallback UI instead of crashing the entire application. This contains failures to affected sections while keeping the rest of the app functional.

Example

This example demonstrates an error boundary component that catches rendering errors and displays a fallback UI instead of crashing the entire application.

class ErrorBoundary extends React.Component {
  // Track whether an error has occurred
  state = { hasError: false };

  // Called when a child component throws an error during rendering
  static getDerivedStateFromError(error) {
    // Update state to trigger fallback UI
    return { hasError: true };
  }

  render() {
    // Show fallback UI if an error was caught
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    // Render children normally if no error
    return this.props.children;
  }
}

Benefits

  • Prevents entire application crashes from isolated component errors.
  • Provides graceful degradation with fallback UI for broken sections.
  • Isolates failures to specific parts of the UI tree.
  • Can log errors to monitoring services for debugging.
  • Improves user experience by keeping functional parts working.

Tradeoffs

  • Only catches errors in render, not in event handlers or async code.
  • Requires React class components, not available as hooks.
  • Can hide bugs if fallback UI is too generic or unclear.
  • May mask underlying issues that should be fixed.
  • Requires strategic placement to balance granularity and coverage.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.