Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 132 ยท Data and Async

Error Boundaries

Learn React error boundaries - getDerivedStateFromError, componentDidCatch, resetting, where to place them, what they do not catch, and the onCaughtError root option.

Rendering is a calculation, and calculations can fail. A component reads user.name when user is null, a list item has a shape nobody expected, or a promise that a component reads with use rejects. In React, an error thrown while rendering cannot be ignored: React has no way to display half of a component. If nothing handles it, React unmounts the entire tree and the user stares at a blank page.

An error boundary is a component that catches errors thrown by its children while they render, shows a fallback instead, and keeps the rest of the app alive. Think of it as a try/catch for a region of the screen. It is the companion of Suspense: Suspense handles "not ready yet", an error boundary handles "it broke".

The one place you still write a class

Here is the surprise. In a React tutorial that teaches hooks and function components only, error boundaries are the single exception. React has no hook for catching render errors. The two lifecycle methods that do the job, static getDerivedStateFromError and componentDidCatch, exist only on class components. Most teams write one boundary class once (or install a library) and never touch classes again.

A boundary is any class component that defines at least one of those two methods:

  • static getDerivedStateFromError(error) runs during rendering after a child threw. It must be a pure function that returns the new state (for example { error }). Use it to switch to the fallback UI.
  • componentDidCatch(error, info) runs after the fallback has been committed. Use it for side effects such as reporting. info.componentStack is a string listing which components were rendering.
A minimal error boundary

Click Toggle explode. The page now says "Something went wrong: Kaboom" next to the still-working toggle button. The boundary replaced only its own children. In the console we saw getDerivedStateFromError: Kaboom twice, then componentDidCatch: Kaboom once, then stack mentions Bomb: true. The doubled first line is a development habit: React renders the failing component once more to check whether the error was a fluke caused by a concurrent update. Because getDerivedStateFromError is a render-phase function, it should be pure, and this is a good reason why. Production builds do not repeat it.

Notice what the render method does: this.props.children is returned when there is no error, and a fallback when there is. That is the entire pattern.

Reading the sequence step by step

  1. A child throws during rendering.
  2. React finds the nearest ancestor boundary and calls its getDerivedStateFromError, which sets error in state.
  3. The boundary re-renders and returns the fallback. The failed subtree is discarded; its state is lost.
  4. After commit, componentDidCatch runs, where you report the error.
  5. Nothing above the boundary re-rendered because of this, and nothing outside it was unmounted.

Placement: how big should a boundary be?

You decide how much of the screen is lost when something breaks, by choosing where to put boundaries.

One boundary per widget

The result reads "Clock works", "Failed: Weather is broken", "News works". With a single boundary around all three, one broken widget would have hidden the other two as well. This run also prints an error line in the console: React logs every caught error with console.error in development, so the preview reports it even though the UI handled it. That is expected, not a second failure.

Useful layers, from outside to inside:

  • Root-level boundary: the last line of defense. Shows "Something went wrong, reload" instead of a blank page.
  • Route or page boundary: a broken page leaves your header and navigation usable.
  • Widget boundary: around independent, optional parts such as a sidebar, a recommendations list or a third-party embed.

Avoid wrapping every single component; fallbacks everywhere are noise. Wrap units that make sense to lose on their own, and where you can offer a meaningful message or a retry.

Resetting a boundary

Once a boundary shows its fallback it stays there, because its error state is set. There are three ways out:

  1. A "Try again" button that clears the state (the first example). Useful when the cause was temporary, such as a failed request.
  2. A key change. Giving the boundary a different key makes React create a brand-new instance with fresh state. Cheap and works with any boundary, including libraries.
  3. Reset keys. The boundary remembers a list of values and clears itself when one changes. This is what the popular library does with resetKeys.

Option 2 is the one you will use most, and it needs no extra code in the boundary. In the next example the boundary gets key={userId}, so choosing another user mounts a fresh boundary with a clean slate. This is exactly the behavior you want when the error depended on that input.

Resetting a boundary with a key

User 3 does not exist, so user.name throws a TypeError and the fallback shows Could not show user: Cannot read properties of undefined (reading 'name'). That wording is Chrome and Edge; other browsers phrase it differently. Press User 1 and the new boundary instance renders Hello, Ada!. Reset keys, the third option, do the same job without remounting: the boundary compares the list of values after each update and clears itself when one changed. You write that by hand with componentDidUpdate, or take it from the library shown below.

A subtle rule: if the error is still thrown after you reset, the boundary catches it again. Resetting does not fix anything by itself; it merely gives the children a chance to render again. Reset when you have changed something (new input, retried request), not blindly.

What error boundaries do not catch

Boundaries only protect rendering: render bodies, lifecycle methods, and constructors of everything below them. They do not catch:

  • Errors in event handlers. Handlers run outside rendering, and a thrown error does not break what is on screen.
  • Asynchronous code such as setTimeout, promises you do not read with use, or fetch callbacks.
  • Errors thrown in the boundary itself (it can only catch for its children; a parent boundary handles it).
  • Errors during server rendering.
Errors a boundary ignores (fails on purpose)

Click the first two buttons and the page does not change at all: no fallback appears. The run reports Error: Handler failed and Error: Timer failed as uncaught errors, and the Count button still works afterwards (we clicked it and saw Count 1). That is the correct behavior, but it means you must handle those errors yourself: try/catch in handlers, .catch() on promises, and a state value that you render.

A very common trick bridges the two worlds: catch the async error, put it in state, and throw it from render, so the boundary handles it uniformly.

JSX
function useThrowToBoundary() {
  const [error, setError] = useState(null);
  if (error) {
    throw error; // thrown during render, so the nearest boundary catches it
  }
  return setError;
}

Use this sparingly. For expected failures (a form with a wrong password, a 404), show regular UI. Boundaries are for the unexpected.

Promises that reject, with Suspense

When a component reads a promise with use, a rejection is thrown during render, so a boundary catches it. Put the boundary outside the Suspense boundary so it can catch failures from components that are still loading:

Suspense plus an error boundary

You first see Loading score..., then Load failed: Server unavailable with a Retry button. Retry creates a new promise (in an event handler, so it is stable) and changes the boundary's key, which resets it. The second attempt resolves and the page shows Score: 42. Note that the promise lives in the App state, created in the initializer or the handler, never inside Score; see the promise identity pitfall.

Reporting errors from the root

A boundary's componentDidCatch can send errors to a service, but React 19 also lets you configure this once, for the whole app, on createRoot:

  • onCaughtError(error, info) is called for errors an error boundary caught.
  • onUncaughtError(error, info) is called for errors no boundary caught (the tree is about to unmount).
  • onRecoverableError(error, info) is called when React recovered by itself (for example a hydration mismatch).
Root-level error callbacks

The page shows Caught: Kaboom and The rest of the page is fine. The console shows onCaughtError: Kaboom, componentStack is a string and errorBoundary is an object. If you remove the ErrorBoundary, the same error goes to onUncaughtError instead and the root unmounts. Defining these callbacks replaces React's default console.error logging for that category, so call your own logger there (and console.error too if you still want the output).

Keep the roles apart: the boundary decides what the user sees; the root callbacks and componentDidCatch decide what you record.

The library version

Writing the class is easy, but most apps use the small react-error-boundary package, which adds a function-friendly API: fallbackRender, resetKeys, onReset, onError, and a useErrorBoundary hook for pushing async errors in. This snippet is read-only, because that package is not available in our editor:

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

function App() {
  return (
    <ErrorBoundary
      fallbackRender={({ error, resetErrorBoundary }) => (
        <div role="alert">
          <p>{error.message}</p>
          <button type="button" onClick={resetErrorBoundary}>Try again</button>
        </div>
      )}
      resetKeys={[userId]}
      onError={(error, info) => reportToService(error, info.componentStack)}
    >
      <UserCard userId={userId} />
    </ErrorBoundary>
  );
}

The hand-written classes in this lesson do the same job, so you have already seen what the library does for you.

Good fallbacks

  • Say what happened in plain words, and offer an action: retry, go back, or contact support.
  • Do not show error.message to end users in production; it can leak internals. We show it here to make the demos readable.
  • Keep the fallback simple. If the fallback itself throws, the error travels up to the next boundary.
  • Make it accessible: role="alert" makes screen readers announce it.
  • Remember that state inside the failed subtree is gone. Design so that losing it is acceptable, or lift important state above the boundary.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these errors will an error boundary catch?

    Boundaries protect rendering. Handlers and async callbacks run outside rendering, so you handle those with try/catch or by putting the error into state.
  2. 2. What is the job of static getDerivedStateFromError?

    It runs during rendering and must be pure; it returns the state (such as { error }) that makes render() show the fallback. Reporting belongs in componentDidCatch or root callbacks.
  3. 3. Why does a boundary stay on its fallback after the cause is fixed?

    The boundary keeps its error state. Clear it with a Try again button, a changed key, or reset keys.
  4. 4. You want a broken sidebar to leave the main article visible. What do you do?

    A boundary replaces only its own children. Placing it around the sidebar isolates that failure. A try/catch around JSX does not catch errors that happen when the child renders.
  5. 5. Which root option is called when no error boundary caught an error?

    onUncaughtError receives errors nobody handled; onCaughtError receives those a boundary caught; onRecoverableError is for errors React recovered from itself.

Summary

  • An error boundary is a class component with static getDerivedStateFromError (choose the fallback) and/or componentDidCatch (report). It is the one place classes remain in modern React.
  • It catches errors thrown while its children render, including rejected promises read with use, and shows a fallback while the rest of the app keeps working.
  • It does not catch errors in event handlers, timers or other async code; handle those yourself or throw them from render through state.
  • Place boundaries at the root, per route and around optional widgets; reset them with a button, a changed key or reset keys.
  • In development React may call getDerivedStateFromError more than once per error, so keep it pure.
  • Use onCaughtError, onUncaughtError and onRecoverableError on createRoot to report errors in one place.
  • The react-error-boundary package offers the same ideas with a friendlier API.

Next: Transitions, useTransition and useDeferredValue