Hiprup

What are Error Boundaries in React?

An Error Boundary is a class component that catches JavaScript errors in its child component tree and renders a fallback UI instead of crashing the whole app. Without one, a thrown error during rendering unmounts the entire React tree.

  • Two methodsstatic getDerivedStateFromError sets fallback state; componentDidCatch logs the error to a service.

  • Catches — render errors, lifecycle errors, errors in constructors of children.

  • Does NOT catch — event handlers, async code, server-side rendering, errors in the boundary itself. Use try/catch for those.

  • Class components only — no hook equivalent yet; use the library react-error-boundary for a hook-friendly wrapper.

  • Granularity — wrap each major route or widget separately so one failure doesn't blank the page.

  • Pair with monitoring — ship caught errors to Sentry or similar.

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

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

  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error, errorInfo.componentStack);
    // Send to error reporting service
    errorReporter.log({ error, componentStack: errorInfo.componentStack });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong</h2>
          <button onClick={() => this.setState({ hasError: false })}>
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage
<ErrorBoundary>
  <Dashboard />  {/* If Dashboard crashes, fallback UI shows */}
</ErrorBoundary>

getDerivedStateFromError sets the error state when any child throws. componentDidCatch logs the error with the component stack trace for debugging. The render method shows either the fallback UI or the children.

The 'Try Again' button resets the error state, allowing the children to re-render.

Know what Error Boundaries catch and what they don't (event handlers, async code). Mention react-error-boundary library as the practical solution.

Strategic placement (around sections, not the whole app) shows production thinking.

What are Error Boundaries in React? | Hiprup