React Error Boundary

6.1.1 · active · verified Sun Apr 19

`react-error-boundary` is a lightweight, reusable React component designed to catch JavaScript errors in a component tree, log them, and display a fallback UI without crashing the entire application. It is built on top of React's native error boundary API and supports all React renderers, including React DOM and React Native. The current stable version is 6.1.1, with a regular release cadence addressing bug fixes and minor improvements. Key differentiators include its straightforward API that directly leverages React's built-in error boundary capabilities, offering `fallback`, `FallbackComponent`, and `fallbackRender` props for flexible error UI presentation. It also provides `onReset` and `resetKeys` for handling error recovery, and ships with comprehensive TypeScript types for an improved developer experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of ErrorBoundary with a FallbackComponent and `onReset` to recover from errors. It shows how to trigger and reset an error state.

import React, { useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

interface BombProps { 
  shouldThrow: boolean;
}

function Bomb({ shouldThrow }: BombProps) {
  if (shouldThrow) {
    throw new Error('💥 Kaboom 💥');
  }
  return <p>All good!</p>;
}

function ErrorFallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: 'red' }}>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

export function App() {
  const [hasError, setHasError] = useState(false);
  const [errorCount, setErrorCount] = useState(0);

  const reset = () => {
    setHasError(false);
    setErrorCount(prev => prev + 1);
  };

  return (
    <div>
      <p>Error count: {errorCount}</p>
      <button onClick={() => setHasError(true)}>Cause Error</button>
      <ErrorBoundary
        FallbackComponent={ErrorFallback}
        onReset={reset}
        resetKeys={[errorCount]} // Reset the boundary when errorCount changes
      >
        <Bomb shouldThrow={hasError} />
      </ErrorBoundary>
    </div>
  );
}

view raw JSON →