Skip to main content
Saved

Pattern Resilience Advanced

Error Boundary

A boundary component catches render errors in the components inside it and shows a fallback UI, so the rest of your application doesn’t crash.

Examples
React, Vue, Svelte and native web
Read
4 min

The problem

A malformed API response or a third-party library throwing an unexpected exception can unmount your entire component tree and leave users staring at a blank screen.

The pattern

You can think of error boundaries as try-catch blocks for your component tree. You wrap a section of your UI in a boundary component, and if anything in that section throws while rendering, the boundary shows a fallback UI in its place instead of letting the whole app crash.

Problem

I’ve seen users lose entire forms, along with everything they’d typed, because an unrelated chart component failed to render. The browser console shows a helpful stack trace for developers, but users see nothing useful.

This happens because errors bubble up through your component tree until they hit the root, and then the whole app crashes. Without error boundaries, one broken widget in the footer can break the entire page.

Solution

Everything outside the boundary keeps working, so if your sales chart throws an error, users can still use the navigation and sidebar, and only the chart area shows the fallback.

I recommend layering them, with one error boundary at the app root as a safety net, and smaller boundaries around risky features such as third-party integrations and user-generated content.

React’s error boundaries only catch errors thrown during rendering and in lifecycle methods. They won’t catch errors in event handlers or async code, and Svelte’s boundaries have the same limits. Vue’s onErrorCaptured also catches errors from event handlers and watchers that Vue calls, but code in a setTimeout or a promise that isn’t awaited still needs its own try-catch. Once you’ve caught an error like that, you can still pass it to the boundary, and the last example below does that. Error Handling covers the try-catch side.

Example

React and Vue have built-in APIs for this, and Svelte 5 has the <svelte:boundary> element. Web Components don’t have an equivalent. The browser doesn’t give a custom element a way to catch errors thrown while its children render, so in that version, each child catches its own errors and reports them to the boundary with an event.

Basic Error Boundary

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };

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

  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error, errorInfo);
  }

  resetError = () => this.setState({ hasError: false, error: null });

  render() {
    if (this.state.hasError) {
      const { fallback } = this.props;
      if (typeof fallback === 'function') {
        return fallback(this.state.error, this.resetError);
      }
      return fallback ?? (
        <div className="error-boundary">
          <h1>Something went wrong</h1>
          <button onClick={this.resetError}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <Dashboard />
    </ErrorBoundary>
  );
}

The “Try again” button only clears the boundary’s error state and mounts the children again. Anything the children fetch when they mount gets fetched again, so that kind of failure can recover. But if the data that caused the error comes from outside the boundary, such as a prop, a store, or a cache, the children render with the same data and might throw the same error again right away. For a reset to be useful, it has to change that data too, and the react-error-boundary example further down does this.

Granular Boundaries

With a boundary around each widget, one broken component doesn’t take down the entire dashboard:

function Dashboard() {
  return (
    <ErrorBoundary fallback={<PageError />}>
      <ErrorBoundary fallback={<WidgetError />}>
        <SalesChart />
      </ErrorBoundary>
      <ErrorBoundary fallback={<WidgetError />}>
        <RecentActivity />
      </ErrorBoundary>
      <ErrorBoundary fallback={<WidgetError />}>
        <UserList />
      </ErrorBoundary>
    </ErrorBoundary>
  );
}

Custom Fallback UI

With a render prop, you can write your own fallback UI that has access to the error and the reset function:

<ErrorBoundary
  fallback={(error, reset) => (
    <div>
      <h2>Widget failed to load</h2>
      <p>{error.message}</p>
      <button onClick={reset}>Retry</button>
    </div>
  )}
>
  <ComplexWidget />
</ErrorBoundary>

Using react-error-boundary

The react-error-boundary library gives you a ready-made boundary component, so you don’t need to write a class component yourself. Its onReset prop runs when users click “Try again”, which is where you can clear the data that caused the error, and resetKeys clears the error automatically when one of the listed values changes:

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

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

function DashboardPage({ userId }) {
  return (
    <ErrorBoundary
      FallbackComponent={ErrorFallback}
      onError={logErrorToService}
      // Drop the cached data, so Dashboard fetches it again
      onReset={() => dashboardCache.clear()}
      // Viewing a different user also clears the error
      resetKeys={[userId]}
    >
      <Dashboard userId={userId} />
    </ErrorBoundary>
  );
}

Errors from Event Handlers and Async Code

A React boundary doesn’t catch an error thrown in an event handler or after an await, because it isn’t thrown while rendering. You can catch it yourself and pass it to the nearest boundary with the library’s useErrorBoundary hook. Without the library, you can store the error in state and throw it again during render, which has the same effect.

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

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

  async function handleClick() {
    try {
      await saveDraft(draft);
    } catch (error) {
      showBoundary(error); // The nearest boundary shows its fallback
    }
  }

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

Benefits

  • If one component fails, users can keep using the navigation and the features that still work.
  • Users see a helpful fallback, such as “This widget failed to load,” instead of a blank white page.
  • If you connect the boundary to Sentry or another monitoring tool, errors are logged automatically, so you hear about production errors as they happen.
  • A retry button lets users recover without refreshing the page, as long as the reset also reloads or clears the data that caused the error.
  • You can show friendly messages to users while logging detailed stack traces for developers.

Tradeoffs

  • Error boundaries mostly catch errors during rendering and lifecycle methods. Async code, along with event handlers in React and Svelte, still needs its own try-catch before the error can be passed to a boundary.
  • In React, error boundaries have to be class components, though react-error-boundary lets you avoid writing classes yourself.
  • A generic “Something went wrong” message can hide bugs from the team, so the boundary should log enough detail for developers to debug them.
  • It can be hard to decide where to put boundaries. With too few, one error replaces a large part of the page with a fallback, and with too many, you end up with fallback UI everywhere.

Summary

An error boundary catches errors thrown while part of your component tree renders, and shows a fallback UI for that part only. With boundaries around risky code, such as third-party widgets, an error only breaks a small part of the page, and users can keep using the rest.

See also

Next in Resilience Error Handling Catching errors from failed API requests and showing users a clear message about what went wrong and what they can do next.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.