React Error Boundary for Functional Components

An error boundary is a React component that catches errors thrown while its children render, and shows a fallback UI instead of crashing the whole page. Here's the catch: React only lets a class component be an error boundary. There's no hook for it, so with function components you either write one small class or use the react-error-boundary package.

Why you need one

Imagine a profile page where one widget reads user.address.city, but for some users address is missing. That throws during render. Without an error boundary, React unmounts the entire tree, and the user sees a blank white page because of one small widget.

An error boundary limits the damage. It says: "if something below me crashes, show this fallback, and leave the rest of the page alone."

The idea: a try/catch for the component tree

You can think of an error boundary as a try/catch for JSX. A normal try/catch can't wrap JSX, because rendering happens later, when React calls your components. So React gives you a component that does the catching for you.

How a React error boundary catches a render error and shows a fallback UI

Step by step:

  1. A component deep in the tree throws while rendering.
  2. React looks up the tree for the nearest error boundary.
  3. That boundary switches to its fallback UI.
  4. Everything outside the boundary keeps working.

Why can't a function component do this?

An error boundary needs two special class methods:

  • static getDerivedStateFromError(error) runs during rendering. You return new state so the next render shows the fallback.
  • componentDidCatch(error, info) runs after the error is caught. This is where you log it, for example to an error-tracking service.

There is no hook version of either one. React's docs say to write a class for this, and to write it once and reuse it.

Writing the class once

import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

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

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

Everything else in your app can stay function components:

function App() {
  return (
    <ErrorBoundary fallback={<p>Something went wrong.</p>}>
      <Profile />
    </ErrorBoundary>
  );
}

getDerivedStateFromError runs during rendering, so keep side effects like logging out of it and put them in componentDidCatch.

The easy way: react-error-boundary

The react-error-boundary package gives you a ready-made boundary that works nicely with function components:

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

function Fallback({ error, resetErrorBoundary }) {
  return (
    <div role="alert">
      <p>Something went wrong: {error.message}</p>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

function App() {
  return (
    <ErrorBoundary
      FallbackComponent={Fallback}
      onError={(error, info) => logToServer(error, info)}
    >
      <Profile />
    </ErrorBoundary>
  );
}

It supports fallback (static content), FallbackComponent, fallbackRender, an onError callback for logging, and onReset and resetKeys for resetting.

What error boundaries don't catch

This is the most common interview follow-up, and the most common source of "my error boundary isn't working" bugs.

What a React error boundary catches and what it misses

Boundaries catch errors during rendering, in lifecycle methods, and in constructors of the components below them. They do not catch:

  • Event handlers. An error in onClick doesn't happen during rendering, so React doesn't route it to a boundary. Use try/catch.
  • Asynchronous code, like setTimeout callbacks or a rejected fetch promise.
  • Errors in the boundary itself. It can only catch errors from its children. An error in its own render goes to the next boundary up.

Sending async errors to a boundary

With react-error-boundary, the useErrorBoundary hook gives you showBoundary, which pushes any error into the nearest boundary. It must be used inside an ErrorBoundary.

import { useErrorBoundary } from 'react-error-boundary';

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

  async function handleClick() {
    try {
      await save();
    } catch (error) {
      showBoundary(error);
    }
  }

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

Resetting a boundary

Once a boundary shows its fallback, it stays that way until it's reset. Otherwise the user would be stuck on the error screen even after the cause is gone.

Resetting a React error boundary with resetKeys

With react-error-boundary you have two options:

  • Call resetErrorBoundary from the fallback, for example from a "Try again" button.
  • Pass resetKeys. When any value in the array changes, the boundary resets itself and tries to render its children again.
<ErrorBoundary FallbackComponent={Fallback} resetKeys={[userId]}>
  <Profile userId={userId} />
</ErrorBoundary>

Here, when the user navigates to a different userId, the boundary resets automatically.

Examples

1. A boundary that doesn't catch an onClick error

<ErrorBoundary fallback={<p>Oops</p>}>
  <button onClick={() => { throw new Error('boom'); }}>Click</button>
</ErrorBoundary>

Problem: the fallback never appears.

Why: the error happens in an event handler, after rendering is done, so the boundary isn't involved.

Fix: wrap the handler in try/catch, and call showBoundary(error) if you want the fallback UI.

2. The boundary is below the crash

function Profile() {
  return (
    <ErrorBoundary fallback={<p>Oops</p>}>
      <p>{user.address.city}</p>
    </ErrorBoundary>
  );
}

Problem: the whole page still crashes.

Why: the error is thrown by Profile itself while rendering user.address.city, and that happens above the boundary. A boundary only protects its children.

Fix: move the boundary up, so it wraps Profile from outside.

3. A fallback that can't recover

<ErrorBoundary FallbackComponent={Fallback}>
  <Profile userId={userId} />
</ErrorBoundary>

Problem: the user switches to another profile, but the error screen stays.

Why: the boundary keeps its error state until it's reset.

Fix: add resetKeys={[userId]} so a new user resets the boundary.

Interview answer

An error boundary is a component that catches errors thrown while its children render and shows a fallback UI instead of unmounting the whole tree. It has to be a class component, because it relies on getDerivedStateFromError and componentDidCatch, which have no hook equivalent. In a function-component app I write one boundary class once, or use react-error-boundary. Boundaries don't catch errors in event handlers, async code, or the boundary itself, so those need try/catch, or showBoundary to forward them to a boundary.

Summary

  • An error boundary catches render errors in its children and shows a fallback UI.
  • It must be a class component. There's no hook for it.
  • It uses getDerivedStateFromError to switch to the fallback and componentDidCatch to log.
  • react-error-boundary lets you use boundaries without writing classes.
  • Boundaries don't catch errors in event handlers, async code, or themselves.
  • Use showBoundary from useErrorBoundary to send those errors to a boundary.
  • A boundary only protects what's below it. Place it above the component that might crash.
  • Use a top-level boundary plus smaller ones around independent sections.
  • Reset with resetErrorBoundary or resetKeys.
  • Without any boundary, an uncaught render error unmounts the whole tree.