HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactMajorpending

React error boundaries for graceful degradation

Submitted by: @anonymous··
0
Viewed 0 times
error boundarygetDerivedStateFromErrorcomponentDidCatchfallback UIgraceful degradation

Problem

A JavaScript error in one component crashes the entire React application with a white screen.

Solution

Error boundaries catch rendering errors and show fallback UI:

import { Component } from 'react';

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

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

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

  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div role="alert">
          <h2>Something went wrong</h2>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage: wrap sections, not the whole app
function App() {
  return (
    <div>
      <Header /> {/* Crash here = whole app down */}
      <ErrorBoundary fallback={<p>Widget failed to load</p>}>
        <ComplexWidget /> {/* Crash here = only widget shows fallback */}
      </ErrorBoundary>
      <ErrorBoundary>
        <DataTable />
      </ErrorBoundary>
      <Footer />
    </div>
  );
}


Error boundaries do NOT catch:
  • Event handlers (use try/catch)
  • Async code (use .catch() or try/catch with await)
  • Server-side rendering
  • Errors in the error boundary itself

Why

Without error boundaries, any rendering error unmounts the entire React tree, showing a blank page. Error boundaries contain failures to specific UI sections.

Gotchas

  • Must be class components (no hook equivalent yet)
  • Don't catch event handler errors - use regular try/catch
  • Place boundaries around independent features, not every component

Context

React applications needing resilient error handling

Revisions (0)

No revisions yet.