React Error Boundaries

By Published 7 min read

React Error Boundaries

Introduction:

In the last lesson, useTransition and useDeferredValue, we kept the app smooth while it did heavy work. Today we handle a different problem: what happens when a component crashes?

Bugs happen. An API returns a user without a name, a value is undefined when you expected an array, and a component throws an error while it renders. In React, an error like that does not just break one component. By default, React removes the whole app from the screen and the user sees a blank white page.

Error boundaries fix this. An error boundary is a component that catches errors in the components below it and shows a fallback UI instead, while the rest of the app keeps working. In this lesson you will build one, add a “Try again” button, reset it automatically, and learn exactly what it can and cannot catch.

All examples were tested with React 19 in Chromium, and the results shown are real.

What Happens Without an Error Boundary?

Here is a small shop page. The Profile component expects a user with a name:

function Profile({ user }) {
  return <h2>{user.name.toUpperCase()}</h2>;
}

function App() {
  return (
    <div>
      <h1>Shop</h1>
      <Profile user={{}} />
      <footer>footer</footer>
    </div>
  );
}

The user object has no name, so user.name.toUpperCase() throws Cannot read properties of undefined (reading 'toUpperCase').

When we ran this, the root element was completely empty afterwards: no heading, no footer, nothing. React’s rule is simple: if an error is not caught, it is safer to show nothing than to show a broken, half-updated UI. Imagine a banking app that shows the wrong balance because half of the screen failed to update.

The fix is not to show nothing, but to show something useful for just the broken part.

Building an Error Boundary:

Error boundaries are the one feature in modern React that still needs a class component. There is no hook for it yet. A class becomes an error boundary when it has one or both of these methods:

  • static getDerivedStateFromError(error): returns new state so the next render shows the fallback.
  • componentDidCatch(error, info): runs after the error is caught. Use it to log the error.
import { Component } from "react";

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

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    // Send it to your logging service here
    console.error(error.message, info.componentStack);
  }

  render() {
    if (this.state.error) {
      return <p role="alert">Something went wrong.</p>;
    }
    return this.props.children;
  }
}

Now wrap the risky part of the page:

function App() {
  return (
    <section>
      <ErrorBoundary>
        <Profile user={{ name: "Aisha" }} />
      </ErrorBoundary>
      <ErrorBoundary>
        <Profile user={{}} />
      </ErrorBoundary>
      <p>Sidebar still works</p>
    </section>
  );
}

The page now shows:

AISHA
Something went wrong.
Sidebar still works

Only the broken profile was replaced. The good profile and the sidebar kept working.

info.componentStack tells you which component failed. In our test it contained Profile, which makes the error much easier to find in your logs.

Adding a “Try Again” Button:

A fixed message is fine, but often the user can recover: a network blip, a temporary bad value. Let’s let the parent decide what the fallback looks like, and give it a reset function:

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

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.error(error.message, info.componentStack);
  }

  reset = () => this.setState({ error: null });

  render() {
    if (this.state.error) {
      if (this.props.fallback) {
        return this.props.fallback({ error: this.state.error, reset: this.reset });
      }
      return <p role="alert">Something went wrong.</p>;
    }
    return this.props.children;
  }
}

Here is a counter with a bug: it crashes when the count reaches 3.

function BuggyCounter() {
  const [count, setCount] = useState(0);
  if (count === 3) throw new Error("Counter crashed at 3");
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

<ErrorBoundary
  fallback={({ error, reset }) => (
    <div role="alert">
      <p>Oops: {error.message}</p>
      <button onClick={reset}>Try again</button>
    </div>
  )}
>
  <BuggyCounter />
</ErrorBoundary>

What happened in our test:

After 3 clicks:   "Oops: Counter crashed at 3" + "Try again" button
After Try again:  "Count: 0"

Notice the count went back to 0, not 3. When a component crashes, React throws away its state. On reset, BuggyCounter mounts again as a brand new component. That is usually what you want, because the old state may be what caused the crash.

Resetting Automatically with a Key:

Sometimes the error belongs to some data, like the selected user. When the user picks another item, the error box should go away by itself. The easiest way is the key prop. When a key changes, React throws away the old component and creates a new one, with fresh state.

function UserPage() {
  const [userId, setUserId] = useState(1);
  const users = { 1: { name: "Aisha" }, 2: {} }; // user 2 has broken data

  return (
    <section>
      <button onClick={() => setUserId(1)}>User 1</button>
      <button onClick={() => setUserId(2)}>User 2</button>
      <ErrorBoundary key={userId}>
        <Profile user={users[userId]} />
      </ErrorBoundary>
    </section>
  );
}

Our test:

User 1:          AISHA
User 2:          Something went wrong.
Back to user 1:  AISHA

Without the key, the boundary would still be in its error state after switching back to user 1, and the user would be stuck.

What Error Boundaries Do NOT Catch:

This part surprises many developers. Error boundaries catch errors thrown while React is rendering, in lifecycle methods, and in effects. They do not catch:

1. Errors in event handlers:

<button onClick={() => { throw new Error("click error"); }}>Raw</button>

In our test the boundary around this button did nothing. The error went straight to the browser as an uncaught error, and the fallback never appeared. Event handlers do not run during rendering, so React does not need to protect the UI: the screen is still valid.

2. Asynchronous code:

Errors inside setTimeout, promises or async functions happen later, outside rendering. A boundary cannot see them.

3. Errors in the boundary itself:

A boundary catches errors in its children, not in its own render. If the fallback crashes, the error goes up to the next boundary above it.

4. Server-side rendering errors:

On the server, these errors are handled by the framework (for example, Next.js has its own error.js files, which are built on error boundaries).

Showing handler errors in the boundary:

If you want an event handler or async error to show the boundary’s fallback, catch it and throw it again during render using state:

function SaveButton() {
  const [error, setError] = useState(null);
  if (error) throw error; // now it happens during render, so the boundary sees it

  async function save() {
    try {
      await saveToServer();
    } catch (e) {
      setError(e);
    }
  }

  return <button onClick={save}>Save</button>;
}

In our test, clicking Save with a failing request showed Caught: Save failed in the boundary’s fallback. Use this only for errors that really should replace the UI. For a normal “could not save, please retry” message, just show it inside the component.

Where Should You Put Error Boundaries?

You do not need one around every component, and one around the whole app is not enough on its own. A good setup has a few levels:

  • One at the top of the app, with a friendly full-page “Something went wrong, reload the page” message. This replaces the white screen.
  • One per page or route, so a broken page does not take down the navigation and layout.
  • One around independent widgets: a comments section, a chart, a recommendations sidebar, a third-party embed. If the chart fails, the article should still be readable.

Think about it from the user’s side: “If this part breaks, what should still work?” Put a boundary around that part.

Logging Errors in React 19:

componentDidCatch is the classic place to send errors to a service like Sentry. React 19 also lets you handle errors for the whole app in one place, with options on createRoot:

import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"), {
  onCaughtError(error, info) {
    // an error boundary caught it
    reportError(error, info.componentStack);
  },
  onUncaughtError(error, info) {
    // nothing caught it, the app was removed from the screen
    reportError(error, info.componentStack);
  },
});

root.render(<App />);

In our test, every error a boundary caught also reached onCaughtError, and the crash in the app without a boundary reached onUncaughtError. This is the best place for one central logging call.

Do You Have to Write the Class Yourself?

No. Many teams use the small react-error-boundary package, which gives you a ready-made <ErrorBoundary> component with FallbackComponent, onReset and resetKeys props, plus a useErrorBoundary hook for showing async errors. It does exactly what we built in this lesson. Writing your own first is a great way to understand what it does under the hood.

Common Mistakes to Avoid:

1. Expecting it to catch click errors:

Use try/catch in event handlers, or the state trick shown above.

2. Only one boundary for the whole app:

Then any small bug replaces the entire page with an error message. Add boundaries around independent sections too.

3. Hiding errors without logging them:

A fallback that says “Something went wrong” but never reports the error means you never find out about the bug. Always log in componentDidCatch or onCaughtError.

4. No way to recover:

Give users a “Try again” button, or reset with key when the data changes.

5. Using boundaries instead of handling expected cases:

If an API can return an empty list or a missing field, handle it in the component (user.name ?? "Guest"). Error boundaries are for unexpected errors.

Conclusion:

Without error boundaries, one render error in React removes your whole app from the screen. An error boundary is a class component with getDerivedStateFromError (to show a fallback) and componentDidCatch (to log). Wrap independent parts of your UI so one broken widget cannot take down the page, give users a way to recover with a reset button or a key, and remember that event handlers and async code need their own try/catch.

In the next React lesson, we will look at React Suspense and Lazy Loading, which handles the other case where a component is not ready to render: when it is still loading.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume