Reactreacterror-boundaryerror-handlingresilienceproduction-ready

Error Boundary with Recovery

A production React error boundary with error reporting, retry logic, fallback UI, and integration with error tracking services.

import { Component, ReactNode, ErrorInfo } from "react";

interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode | ((error: Error, retry: () => void) => ReactNode);
  onError?: (error: Error, errorInfo: ErrorInfo) => void;
  onReset?: () => void;
  resetKeys?: unknown[];
}

interface ErrorBoundaryState {
  error: Error | null;
  errorInfo: ErrorInfo | null;
}

export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState = { error: null, errorInfo: null };

  static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
    return { error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.setState({ errorInfo });
    this.props.onError?.(error, errorInfo);
  }

  componentDidUpdate(prevProps: ErrorBoundaryProps) {
    if (this.state.error && prevProps.resetKeys !== this.props.resetKeys) {
      const hasChanged = this.props.resetKeys?.some(
        (key, i) => key !== prevProps.resetKeys?.[i]
      );
      if (hasChanged) {
        this.reset();
      }
    }
  }

  reset = () => {
    this.props.onReset?.();
    this.setState({ error: null, errorInfo: null });
  };

  render() {
    const { error } = this.state;
    const { children, fallback } = this.props;

    if (error) {
      if (typeof fallback === "function") {
        return fallback(error, this.reset);
      }
      if (fallback) {
        return fallback;
      }
      return <DefaultErrorFallback error={error} onRetry={this.reset} />;
    }

    return children;
  }
}

function DefaultErrorFallback({ error, onRetry }: { error: Error; onRetry: () => void }) {
  return (
    <div role="alert" className="p-6 border border-red-200 rounded-lg bg-red-50">
      <h2 className="text-lg font-semibold text-red-800">Something went wrong</h2>
      <pre className="mt-2 text-sm text-red-600 whitespace-pre-wrap">
        {error.message}
      </pre>
      <button
        onClick={onRetry}
        className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
      >
        Try again
      </button>
    </div>
  );
}

// Hook for programmatic error throwing (async errors)
export function useErrorBoundary() {
  const [, setState] = useState();
  return {
    throwError: (error: Error) => {
      setState(() => { throw error; });
    },
  };
}

title: "Error Boundary with Recovery" description: "A production React error boundary with error reporting, retry logic, fallback UI, and integration with error tracking services." category: "React" language: "typescript" tags: ["react", "error-boundary", "error-handling", "resilience", "production-ready"] createdAt: "2025-02-20" updatedAt: "2025-03-10"

Overview

A robust error boundary component that catches rendering errors, provides recovery via retry, integrates with error tracking services, and auto-resets when specified keys change. Includes a useErrorBoundary hook for throwing async errors into the nearest boundary.

Code

<ErrorBoundary
  fallback={(error, retry) => <ErrorUI error={error} onRetry={retry} />}
  onError={(error) => reportToSentry(error)}
  resetKeys={[routeKey]}
>
  <App />
</ErrorBoundary>

Notes

  • resetKeys auto-resets the boundary when navigation or key props change
  • The onError callback integrates with Sentry, DataDog, or any error tracking service
  • useErrorBoundary hook catches async/event handler errors that class boundaries cannot
  • The fallback function receives both the error and a retry callback for user-initiated recovery
  • Place boundaries at feature boundaries (not around every component) for optimal granularity