React Error Boundary
`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
-
ErrorBoundary cannot be used as a JSX component
cause This error commonly occurs due to a version mismatch between `react` and `@types/react`, or incorrect TypeScript configuration.fixEnsure `react` and `@types/react` versions are exactly matched in your `package.json`. If using npm, use `overrides`. If using yarn, use `resolutions`. Also, verify your `tsconfig.json` `jsx` setting is correct (e.g., `react-jsx`). -
ReferenceError: require is not defined
cause Attempting to import `react-error-boundary` using CommonJS `require()` syntax in a project that is configured for ES modules, or in a version that is ESM-only.fixUpdate your import statements from `const ErrorBoundary = require('react-error-boundary');` to `import { ErrorBoundary } from 'react-error-boundary';`. Ensure your project's `package.json` specifies `"type": "module"` if you intend to use ESM globally, or configure your build tools accordingly. This is a breaking change since v6.0.0. -
Invalid hook call. Hooks can only be called inside of the body of a function component.
cause While `react-error-boundary` provides a functional component interface, it internally relies on React's class-based error boundaries. If you inadvertently try to use hooks directly within the `FallbackComponent` or `fallbackRender` props in a way that violates React's rules (e.g., conditional hooks), this can occur.fixEnsure that any custom `FallbackComponent` or the function passed to `fallbackRender` adheres strictly to React's rules of hooks, calling them unconditionally at the top level of a functional component. If logic requires conditional execution, move it inside an effect or memo hook, or use a custom hook.
Warnings
- breaking Version 6.0.0 made the module ESM-only to align with modern JavaScript tooling. This means `require()` syntax for importing `react-error-boundary` will no longer work.
- breaking Version 5.0.0 updated the TypeScript types for `withErrorBoundary` to be compatible with the latest `forwardRef` types in React. This may cause type errors in projects heavily relying on `withErrorBoundary` with `forwardRef` if not updated.
- gotcha React Error Boundaries (and thus `react-error-boundary`) cannot catch errors in certain scenarios: event handlers, asynchronous code (e.g., `setTimeout`, promises, `async/await`), server-side rendering, or errors thrown within the error boundary component itself.
- gotcha The component provides three different props for rendering a fallback UI: `fallback`, `FallbackComponent`, and `fallbackRender`. Choosing the wrong one can lead to unexpected behavior or unnecessary re-renders.
- gotcha Using `resetKeys` is crucial for resetting an error boundary when the context changes, allowing React to retry rendering. If `resetKeys` are not properly managed, the boundary might remain in an error state even after the underlying cause is resolved.
Install
-
npm install react-error-boundary -
yarn add react-error-boundary -
pnpm add react-error-boundary
Imports
- ErrorBoundary
const ErrorBoundary = require('react-error-boundary')import { ErrorBoundary } from 'react-error-boundary' - withErrorBoundary
import withErrorBoundary from 'react-error-boundary/withErrorBoundary'
import { withErrorBoundary } from 'react-error-boundary' - getErrorMessage
import { getErrorMessage } from 'react-error-boundary'
Quickstart
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>
);
}