`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.
npm install react-error-boundaryVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic usage of ErrorBoundary with a FallbackComponent and `onReset` to recover from errors. It shows how to trigger and reset an error state.
Migrate your import statements from CommonJS `require()` to ES module `import` syntax. Ensure your project is configured for ESM.
Review and update the type definitions for components wrapped with `withErrorBoundary` and `forwardRef` to match the new React type requirements.
For errors in event handlers or asynchronous code, use traditional `try/catch` blocks. Implement server-side error handling separately for SSR. Ensure your fallback UI logic is robust to avoid errors within the boundary itself.
`fallback` is for static content. `FallbackComponent` expects a React component (props: `error`, `resetErrorBoundary`). `fallbackRender` expects a render prop function (args: `{ error, resetErrorBoundary }`). Choose based on whether you need dynamic logic or access to the error/reset function.Pass an array of values to `resetKeys` that, when changed, should trigger a reset of the error boundary. This is often tied to state or props that, if updated, mean the component is ready to try rendering again.
Ensure `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`).
Update 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.Ensure 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.