react-error-boundary vs react-error-overlay
React Error Recovery and Development Diagnostics
react-error-boundaryreact-error-overlaySimilar Packages:

React Error Recovery and Development Diagnostics

A chart can fail to render in a React dashboard while the filters and navigation still work. A failed development build can stop the whole dashboard from loading. Those failures happen in different layers and call for different tools.

react-error-boundary wraps the failing part of the component tree so the user can see a fallback and recover. react-error-overlay belongs to the development toolchain. A dev client such as Create React App’s can show a compiler message or browser stack for a developer to inspect.

Use the component boundary to decide what stays interactive in the shipped app. When maintaining an older development setup, check how its dev client reports and clears diagnostics. The two layers can work together in the same dashboard.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-error-boundary20,878,9537,99652.5 kB02 months agoMIT
react-error-overlay5,413,710103,221385 kB2,4072 years agoMIT

Use a broken sales chart to check two things. In the app, see whether the filters still work and the chart can recover. In development, see whether the dev client puts the error where you can inspect it. If the dashboard never loads, start earlier in the lifecycle and examine the development build or server response.

🧭 Start with who needs to see the failure

SituationUser or developer experienceWhere to handle it
The chart throws during a client renderThe dashboard stays usable around the failed chartA react-error-boundary around the chart renders its fallback
A chart refresh rejects in a click handlerThe chart shows a retry message, or the entire section falls back if it cannot continueHandle the rejection where the request starts, and pass it to showBoundary only when the section needs to fall back
The development build failsA developer sees the compiler message even before the dashboard mountsThe dev client forwards the message to react-error-overlay
A render fails on the serverThe framework handles the request or stream failureUse the framework’s server error handling and logging

🛠️ Give the chart a fallback and a way to recover

Put the filters and navigation outside the boundary if the user should be able to change them when the chart fails. In this example, an invalid input triggers the fallback. Retry replaces that input with a sample value and lets React render the chart again.

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

function Chart({ total }: { total: number | null }) {
  if (total === null) throw new Error('Chart data unavailable');
  return <p>Total orders: {total}</p>;
}

export default function Dashboard() {
  const [total, setTotal] = useState<number | null>(null);

  return (
    <main>
      <h2>Sales dashboard</h2>
      <ErrorBoundary
        onReset={() => setTotal(42)}
        fallbackRender={({ resetErrorBoundary }) => (
          <div role="alert">
            <p>The chart could not load.</p>
            <button onClick={resetErrorBoundary}>Try again</button>
          </div>
        )}
      >
        <Chart total={total} />
      </ErrorBoundary>
    </main>
  );
}

Verify that the heading remains visible, that the fallback belongs to the chart, and that retry restores the chart. In the actual dashboard, onReset can clear a bad selection or invalidate cached data before the next render. If the same input still causes the chart to throw, retry will return to the fallback. Keep the error details for diagnostics and give users a recovery action they can understand.

🔎 Follow the same failure through development

In development, React can expose a caught rendering error to window error handlers, so developer diagnostics can appear while the chart fallback is also taking effect. A compile error takes a different path. The bundler’s dev client already has a build message, and can show it before the React tree exists.

Create React App’s dev client already connects the overlay to both paths. The following adapter shows the responsibilities if you maintain similar custom wiring. The supplied subscribeToBuild registers a callback with your dev client, which passes a formatted error string on failure and null after a successful build.

import overlay from 'react-error-overlay';

export function connectDevelopmentOverlay(subscribeToBuild) {
  overlay.startReportingRuntimeErrors({});

  const unsubscribe = subscribeToBuild((error) => {
    if (error === null) {
      overlay.dismissBuildError();
    } else {
      overlay.reportBuildError(error);
    }
  });

  return () => {
    unsubscribe();
    overlay.stopReportingRuntimeErrors();
  };
}

Call this once from the browser’s development entry point and use the returned cleanup when replacing that client. The overlay displays the message your toolchain supplied. Check the failure and recovery path by introducing a local compile error and fixing it in your dev session. Use the overlay already provided by your dev server when it covers these steps.

🧩 Match recovery to the kind of failure

  • A failed request after a click. For a transient error, a message and retry beside the refresh button may be enough. If the chart cannot be used after the failure, get showBoundary from useErrorBoundary() in a descendant component, then call showBoundary(error) in the request’s error handler. Ordinary promise rejections and event handler errors need this explicit handling. With React Actions, errors thrown inside the function passed to the startTransition returned by useTransition can reach the nearest boundary.
  • An error in the fallback itself. Keep the fallback’s dependencies small. A surrounding boundary can handle a fallback that throws. Test this separately from the original chart error if the fallback performs its own work.
  • An error while rendering on the server. The chart example demonstrates recovery during client rendering. Use the framework’s server error handling for a failed request or stream, and check what response reaches the browser.

✅ Choose by what needs to keep working

For a dashboard customers use, decide which sections should stay interactive and draw the boundary around that recovery unit. For a legacy Create React App project, check that the existing dev client still reports and clears diagnostics after a fix. A project can use both layers. Test them separately so a helpful local overlay does not hide a missing recovery path in the shipped app.

How to Choose: react-error-boundary vs react-error-overlay

  • react-error-boundary:

    Wrap a chart or route section when the rest of the page should stay interactive after a child throws. Give the fallback a recovery action and wire it to the actual state or data that caused the failure.

  • react-error-overlay:

    Use the dev client’s existing integration if you maintain a Create React App project and need browser diagnostics for failed builds or runtime errors. Its usefulness depends on the client sending and dismissing those diagnostics at the right time.

README for react-error-boundary

react-error-boundary logo

react-error-boundary: Reusable React error boundary component. Supports all React renderers (including React DOM and React Native).

If you like this project, 🎉 become a sponsor or ☕ buy me a coffee

[!NOTE] Projects using framework or runtimes that don't support ES Modules should use version 5 of this library.

Getting started

# npm
npm install react-error-boundary

# pnpm
pnpm add react-error-boundary

# yarn
yarn add react-error-boundary

Documentation

Read the react-error-boundary docs for examples, API reference, and troubleshooting. The docs also include a frequently asked questions guide.

Quick start

Wrap an ErrorBoundary around the part of the tree where you want to show a fallback UI if rendering fails. Your fallback can call resetErrorBoundary to clear the error and retry rendering:

"use client";

import { ErrorBoundary, getErrorMessage } from "react-error-boundary";

export default function App() {
  return (
    <ErrorBoundary
      fallbackRender={({ error, resetErrorBoundary }) => (
        <div role="alert">
          <p>Something went wrong:</p>
          <pre>{getErrorMessage(error)}</pre>
          <button onClick={resetErrorBoundary}>Try again</button>
        </div>
      )}
      onError={(error, info) => {
        // Log the error to your error reporting service
      }}
      onReset={() => {
        // Reset any state that may have caused the error
      }}
    >
      {/* Components protected by this boundary */}
    </ErrorBoundary>
  );
}

What errors are caught?

This package is built on top of React error boundaries, so it follows React's rules for what errors are caught.

Error boundaries catch errors thrown while rendering the tree below them.

Error boundaries do not catch errors thrown during:

  • Server side rendering
  • Event handlers
  • Errors thrown in the error boundary itself
  • Async code that runs after rendering, like setTimeout callbacks or unresolved promises

Event handler and async errors

For event handler errors and async callback errors:

  • Use useErrorBoundary to pass caught errors to the nearest boundary.
  • In React 19, useTransition Actions can be an alternative: errors thrown from a function passed to the returned startTransition function are caught by the nearest boundary.
"use client";

import { useTransition } from "react";
import { ErrorBoundary } from "react-error-boundary";

function AddCommentContainer() {
  return (
    <ErrorBoundary fallback={<p>Could not add comment</p>}>
      <AddCommentButton />
    </ErrorBoundary>
  );
}

function AddCommentButton() {
  const [isPending, startTransition] = useTransition();

  function handleClick() {
    startTransition(async () => {
      await addComment();
    });
  }

  return (
    <button disabled={isPending} onClick={handleClick}>
      {isPending ? "Adding..." : "Add comment"}
    </button>
  );
}

API

ErrorBoundary

A reusable React error boundary component. Wrap this component around other React components to "catch" errors and render a fallback UI.

Catches errors thrown while rendering the tree below it.

Does not catch errors thrown during:

  • Server side rendering
  • Event handlers
  • Errors thrown in the error boundary itself
  • Async code that runs after rendering, like setTimeout callbacks or unresolved promises

Event handler and async errors:

  • Use useErrorBoundary to pass caught errors to the nearest boundary
  • In React 19, errors thrown from a function passed to the startTransition function returned by useTransition are caught by the nearest boundary

ℹ️ The component provides several ways to render a fallback: fallback, fallbackRender, and FallbackComponent. Refer to the documentation to determine which is best for your application.

ℹ️ This is a client component. You can only pass props to it that are serializable or use it in files that have a "use client"; directive.

Required props

None

Optional props

NameDescription
onError

Optional callback to enable e.g. logging error information to a server. @param error Value that was thrown; typically an instance of Error @param info React "component stack" identifying where the error was thrown

onReset

Optional callback to be notified when an error boundary is reset so React can retry the failed render.

resetKeys

When changed, these keys will reset a triggered error boundary. This can be useful when an error condition may be tied to some specific state (that can be uniquely identified by key). See the documentation for examples of how to use this prop.

fallback

Static content to render in place of an error if one is thrown.

<ErrorBoundary fallback={<div className="text-red">Something went wrong</div>} />
FallbackComponent

React component responsible for returning a fallback UI based on a thrown value.

<ErrorBoundary FallbackComponent={Fallback} />
fallbackRender

Render prop function responsible for returning a fallback UI based on a thrown value.

<ErrorBoundary fallbackRender={({ error, resetErrorBoundary }) => <div>...</div>} />

FAQ

ErrorBoundary cannot be used as a JSX component

This error can be caused by a version mismatch between react and @types/react. To fix this, ensure that both match exactly, e.g.:

If using NPM:

{
  ...
  "overrides": {
    "@types/react": "17.0.60"
  },
  ...
}

If using Yarn:

{
  ...
  "resolutions": {
    "@types/react": "17.0.60"
  },
  ...
}

This blog post shows more examples of how this package can be used, although it was written for the version 3 API.