30% offEnding soon
All questions

ErrorBoundary

Premium

ErrorBoundary

An error boundary is a React class component that replaces a crashed descendant tree with fallback UI. Implement a reusable ErrorBoundary that captures render and lifecycle errors, reports them, and lets the application recover manually or when a reset key changes. React documents the underlying lifecycle contract in its Component reference.

Signature

type ErrorDetails = {
  error: Error;
  reset: () => void;
};

type ErrorBoundaryProps = {
  children: React.ReactNode;
  fallback?: React.ReactNode | ((details: ErrorDetails) => React.ReactNode);
  onError?: (error: Error, info: React.ErrorInfo) => void;
  resetKeys?: unknown[];
};

class ErrorBoundary extends React.Component<ErrorBoundaryProps> {}

Examples

<ErrorBoundary fallback={<p>Profile unavailable</p>}>
  <Profile />
</ErrorBoundary>

// If Profile throws while rendering, the paragraph replaces Profile.
<ErrorBoundary
  resetKeys={[userId]}
  onError={(error, info) => report(error, info)}
  fallback={({ error, reset }) => (
    <button onClick={reset}>Retry after: {error.message}</button>
  )}
>
  <UserProfile id={userId} />
</ErrorBoundary>

// The button resets manually. A changed userId also retries the children.

Notes

  • Capture descendants — catch errors thrown while a child renders or runs a lifecycle method. Render successful children unchanged.
  • Render a fallback — accept either a React node or a function receiving the exact error and a stable reset function. Render null when fallback is omitted.
  • Report after capture — call onError(error, info) from componentDidCatch. Do not report manual or reset-key recovery as a new error.
  • Compare reset keys shallowly — while failed, reset when the array length or any positional value changes by Object.is. A new array containing the same values must not reset.
  • Keep React's boundary limits — do not try to catch errors from event handlers, ordinary asynchronous callbacks, server rendering, or this boundary's own fallback.