Error boundaries

Topic 1 of 5 in Production patterns7 min readIntermediateFree course

Overview

Bugs happen: an API returns an unexpected shape, a value is undefined where you didn’t expect it, a third-party component throws. In React, an error thrown while rendering that nothing catches unmounts the entire app — the user is left with a blank white page. Error boundaries contain the damage: they catch errors in the part of the tree they wrap and show fallback UI instead.

Inside App, the Header keeps working. One ErrorBoundary wraps CourseList and Sidebar. Another ErrorBoundary wraps a Chart that throws during render; it shows “Couldn’t load the chart” with a Try again button instead. Only the nearest boundary’s area is replaced. Without one, a render error unmounts the whole app.

Why React unmounts everything

It might seem harsh, but showing broken UI is worse than showing none. A half-rendered checkout page that displays the wrong total could cost a user money. So React’s default is: if rendering fails and nobody handles it, remove the UI. Error boundaries let you decide what to show instead.

Using react-error-boundary

React’s built-in error boundary API only exists for class components. Rather than writing a class, almost every project uses the small react-error-boundary package:

Terminal
npm install react-error-boundary
JSX
import { ErrorBoundary } from 'react-error-boundary';

function ChartError({ error, resetErrorBoundary }) {
  return (
    <div role="alert">
      <p>Couldn’t load the chart.</p>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

<ErrorBoundary FallbackComponent={ChartError}>
  <SalesChart />
</ErrorBoundary>

If SalesChart (or anything inside it) throws while rendering, the boundary renders ChartError instead. Everything outside the boundary keeps working.

Three ways to give the fallback:

  • fallback={<p>Something went wrong</p>} — static JSX,
  • FallbackComponent={ChartError} — a component receiving error and resetErrorBoundary,
  • fallbackRender={({ error, resetErrorBoundary }) => …} — an inline function.

Retrying

resetErrorBoundary() clears the error and renders the children again — useful when the failure was temporary. Use onReset to reset any state that caused the error, and resetKeys to reset automatically when something changes:

JSX
<ErrorBoundary FallbackComponent={CourseError} resetKeys={[courseId]}>
  <CourseDetails courseId={courseId} />
</ErrorBoundary>

Navigate to another course and the boundary resets itself, giving the new course a fresh try.

What boundaries catch — and don’t

Error boundaries catch errors thrown during rendering of the components below them — including in hooks and lifecycle code and in rejected promises read with use. They do not catch errors in:

  • event handlers (they don’t run during rendering),
  • async code like setTimeout callbacks or unawaited promises,
  • server-side rendering,
  • the error boundary itself (it’s handled by the next boundary up).

Routing async errors to a boundary

For event handlers, the usual approach is to handle errors locally — show a message near the button. When you’d rather show the boundary’s fallback, there are two ways:

JSX
// 1. Actions in a transition: errors thrown inside reach the nearest boundary
const [isPending, startTransition] = useTransition();

function handleRefresh() {
  startTransition(async () => {
    await refreshLessons();        // if this throws, the boundary shows its fallback
  });
}
JSX
// 2. useErrorBoundary from react-error-boundary
import { useErrorBoundary } from 'react-error-boundary';

function ExportButton() {
  const { showBoundary } = useErrorBoundary();

  async function handleExport() {
    try {
      await exportReport();
    } catch (error) {
      showBoundary(error);
    }
  }

  return <button onClick={handleExport}>Export</button>;
}

Where to put boundaries

Think about how much of the screen should disappear when something fails:

  • One at the top of the app, with a friendly “Something went wrong — reload” page. This is your last line of defence; never ship without it.
  • One per route (routers provide this — React Router’s route ErrorBoundary, Next.js error.js files), so the navigation stays usable.
  • Around independent widgets — charts, comments, recommendations — so one failing feature doesn’t take the page down.

Don’t wrap every component: too many boundaries scatter error messages across the page, and users can’t tell what’s broken.

Reporting errors

Users rarely report errors; you need to know about them anyway. Send them to a monitoring service like Sentry, Datadog or your own logging endpoint:

JSX
<ErrorBoundary
  FallbackComponent={AppError}
  onError={(error, info) => {
    reportError(error, { componentStack: info.componentStack });
  }}
>
  <App />
</ErrorBoundary>

React 19 also lets you hook into errors for the whole app at the root:

JSX
createRoot(document.getElementById('root'), {
  onCaughtError: (error, info) => reportError(error, info),     // caught by a boundary
  onUncaughtError: (error, info) => reportError(error, info),   // not caught — app unmounted
  onRecoverableError: (error) => console.warn(error),            // React recovered automatically
}).render(<App />);

The class component API

For reference, here’s what react-error-boundary does under the hood — you’ll see this in older codebases:

JSX
import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };                     // render the fallback next
  }

  componentDidCatch(error, info) {
    reportError(error, info.componentStack);
  }

  render() {
    if (this.state.error) return this.props.fallback;
    return this.props.children;
  }
}

Writing good fallback UI

  • Say what went wrong in plain language, and what the user can do: “Couldn’t load your progress. Try again, or check your connection.”
  • Offer a retry where it might help.
  • Keep the rest of the page usable — navigation, other widgets.
  • In development, show error.message to help debugging; in production, don’t expose stack traces to users.

Errors are part of the design. Decide what users see when each part of the page fails, the same way you design loading and empty states.

Exercise

A resilient dashboard

Using react-error-boundary, wrap each dashboard widget (ProgressChart, RecentLessons) in its own ErrorBoundary with a WidgetError fallback that shows “This widget couldn’t load.” and a “Try again” button calling resetErrorBoundary. Log errors with onError to a reportError(error, info) function. Then make a “Refresh” button inside RecentLessons whose async click handler failure is shown by the boundary (use useTransition, or useErrorBoundary().showBoundary).

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

// provided: ProgressChart, RecentLessons, reportError, refreshLessons

function WidgetError(/* props */) {
  // your code here
}

export function Dashboard() {
  // your code here
}

Summary

  • Without an error boundary, an error thrown while rendering unmounts the whole React app.
  • An error boundary catches render errors in its subtree and shows a fallback; only that area is replaced.
  • React’s built-in boundaries are class components; most apps use the react-error-boundary package.
  • Boundaries don’t catch event-handler or async errors directly — use transitions or showBoundary to route them there.
  • Place boundaries around independent features, offer a retry, and report errors to a monitoring service.