TExcelTAD
Home › React › React Error Boundaries

React Error Boundaries

If a component throws an error while rendering, React has no safe UI to show — by default it unmounts the whole app, leaving a blank page. An error boundary is a component that catches errors in its subtree and displays a fallback instead, so one broken widget doesn't take down everything else.

Writing an error boundary

Error boundaries are the one feature that still requires a class component. It implements one or both of these methods:

Method Purpose
static getDerivedStateFromError(error) return new state so the next render shows the fallback
componentDidCatch(error, info) side effects such as logging; info.componentStack shows where it happened
jsx · try it yourself
import { Component, useState } from 'react';

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

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

  componentDidCatch(error, info) {
    console.log('Logged to error service:', error.message);
  }

  render() {
    if (this.state.error) {
      return (
        <div style={{ background: '#fdecea', border: '1px solid #f5c2c0', padding: 10, borderRadius: 6 }}>
          😵 Something went wrong: {this.state.error.message}
        </div>
      );
    }
    return this.props.children;
  }
}

function Profile({ user }) {
  return <p>👤 {user.name.toUpperCase()}</p>;   // crashes when user is null
}

export default function App() {
  const [user, setUser] = useState({ name: 'Hoa' });
  return (
    <div>
      <button onClick={() => setUser(null)}>Break the profile</button>
      <ErrorBoundary>
        <Profile user={user} />
      </ErrorBoundary>
      <p>This text is outside the boundary and keeps working.</p>
    </div>
  );
}

Note: In development, React also prints the caught error to the console (and Vite shows an overlay). That's expected — the boundary still renders the fallback.

Reusable boundary with reset

A good boundary accepts a fallback and offers a way to try again. Resetting the state re-renders the children:

jsx · try it yourself
import { Component, useState } from 'react';

class ErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) {
    return { error };
  }
  reset = () => this.setState({ error: null });
  render() {
    if (this.state.error) return this.props.fallback(this.state.error, this.reset);
    return this.props.children;
  }
}

function Widget({ name, failRate }) {
  if (failRate > 0.5) throw new Error(`${name} failed to render`);
  return <div style={{ padding: 10, background: '#e8f5e9', borderRadius: 6 }}>✅ {name} is fine</div>;
}

function Card({ name }) {
  const [failRate, setFailRate] = useState(0);
  return (
    <div style={{ border: '1px solid #ccc', padding: 8, borderRadius: 8, width: 220 }}>
      <ErrorBoundary
        fallback={(error, reset) => (
          <div style={{ padding: 10, background: '#fff3e0', borderRadius: 6 }}>
            ⚠️ {error.message}
            <br />
            <button onClick={() => { setFailRate(0); reset(); }}>Try again</button>
          </div>
        )}
      >
        <Widget name={name} failRate={failRate} />
      </ErrorBoundary>
      <button onClick={() => setFailRate(1)} style={{ marginTop: 6 }}>Crash {name}</button>
    </div>
  );
}

export default function App() {
  return (
    <div style={{ display: 'flex', gap: 10 }}>
      <Card name="Weather" />
      <Card name="Stocks" />
      <Card name="News" />
    </div>
  );
}

Crash one widget: only that card shows its fallback, and the others keep working.

What boundaries do NOT catch

Error boundaries catch errors thrown during rendering, in lifecycle methods and in constructors of the tree below them. They don't catch:

Not caught Handle it with
errors in event handlers try/catch inside the handler, then set error state
async code (setTimeout, promises) .catch / try/catch with await, then set state
errors in the boundary itself a boundary higher up
server-side rendering errors your framework's error handling

A handy trick lets async or event errors reach a boundary: catch them and re-throw during render through state.

jsx · try it yourself
import { Component, useState } from 'react';

class ErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) {
    return { error };
  }
  render() {
    return this.state.error ? <p style={{ color: 'crimson' }}>Boundary caught: {this.state.error.message}</p> : this.props.children;
  }
}

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

  function handleClick() {
    setTimeout(() => {
      try {
        throw new Error('Network timeout while saving');
      } catch (err) {
        setError(err);
      }
    }, 500);
  }

  return <button onClick={handleClick}>Save (fails after 0.5s)</button>;
}

export default function App() {
  return (
    <ErrorBoundary>
      <SaveButton />
    </ErrorBoundary>
  );
}

Where to place boundaries

  • Top level: one around the whole app shows a friendly "Something went wrong — reload" page instead of a blank screen.
  • Per feature: around independent widgets, panels or routes, so a failure stays contained.
  • Around third-party components you don't control.

Tip: Many projects use the small react-error-boundary package, which provides a ready-made <ErrorBoundary FallbackComponent={…} onReset={…}> and a useErrorBoundary hook, so you don't have to write the class yourself.

React 19 root error callbacks

React 19 adds options to createRoot for app-wide reporting: onCaughtError (caught by a boundary), onUncaughtError (not caught) and onRecoverableError. They're a good place to send errors to a monitoring service.

Test yourself

Which kind of component can be an error boundary?

  1. Any function component
  2. A class component with getDerivedStateFromError or componentDidCatch
  3. Only the root App component
  4. A component using useError()

Does an error boundary catch an error thrown inside an onClick handler?

  1. Yes
  2. No — use try/catch in the handler
  3. Only in production
  4. Only if the handler is async

What happens to an app without any error boundary when a component throws during render?

  1. Only that component disappears
  2. React unmounts the entire tree
  3. React retries forever
  4. The error is silently ignored