reactjs
/

React Error Boundaries – Graceful Error Handling

Last Sync: Today

On this page

4
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Error Boundaries – Graceful Error Handling

What is an Error Boundary?

In the past, a JavaScript error inside a component would corrupt React’s internal state and cause the entire application to vanish (the 'White Screen of Death'). Error Boundaries are special components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the crashed component tree.

The Catch: Class Components Only

As of 2026, Error Boundaries must still be written as Class Components. There is no functional hook equivalent (like useError) because the lifecycle methods getDerivedStateFromError and componentDidCatch are unique to classes. Most developers write one 'Global' boundary and several 'Feature' boundaries.

React JSXRead-only
1
import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  // 1. Update state so the next render shows the fallback UI
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  // 2. Log the error to a service like Sentry or LogRocket
  componentDidCatch(error, errorInfo) {
    console.error('Logging to service:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

What Error Boundaries Do NOT Catch

Error Boundaries are powerful but they are not a universal 'try-catch'. They specifically catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

  • Event handlers: (e.g., onClick errors). Use regular try/catch blocks here.
  • Asynchronous code: (e.g., setTimeout or requestAnimationFrame callbacks).
  • Server-side rendering.
  • Errors thrown in the boundary itself (rather than its children).

Strategy: Granular Boundaries

Don't just wrap your App in one boundary. Wrap individual heavy features (like a Dashboard Chart or a Search Sidebar) so that if one fails, the rest of the application remains interactive.

React JSXRead-only
1
<Layout>
  <Header />
  <ErrorBoundary fallback={<p>Sidebar failed to load.</p>}>
    <Sidebar />
  </ErrorBoundary>
  <MainContent />
</Layout>

Try it yourself

import React, { useState } from 'react';

// A component that crashes when it gets to 5
const BuggyCounter = () => {
  const [counter, setCounter] = useState(0);

  if (counter === 5) {
    throw new Error('I crashed!');
  }

  return (
    <button onClick={() => setCounter(c => c + 1)}>
      Click to reach 5: {counter}
    </button>
  );
};

class SimpleErrorBoundary extends React.Component {
  state = { hasError: false };

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

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ color: 'red', padding: '10px', border: '1px solid red' }}>
          <h4>⚠️ This section crashed.</h4>
          <button onClick={() => this.setState({ hasError: false })}>
            Reset & Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

export default function App() {
  return (
    <div style={{ padding: '20px' }}>
      <h3>Error Boundary Demo</h3>
      <p>The boundary protects the rest of the app.</p>
      <SimpleErrorBoundary>
        <BuggyCounter />
      </SimpleErrorBoundary>
      <p style={{ marginTop: '20px' }}>I am outside the boundary and still working!</p>
    </div>
  );
}

Test Your Knowledge

Q1
of 3

Which lifecycle method is used to render a fallback UI after an error?

A
componentDidCatch
B
getDerivedStateFromError
C
shouldComponentUpdate
D
componentWillUnmount
Q2
of 3

Can Error Boundaries catch errors in an onClick handler?

A
Yes, always
B
Only in development
C
No, you must use try/catch in handlers
D
Only if using React 18+
Q3
of 3

What happens if a component crashes and there is NO error boundary?

A
React shows a warning but keeps running
B
The component just disappears
C
The entire React component tree is unmounted (White Screen)
D
The browser reloads the page

Frequently Asked Questions

Why use Error Boundaries instead of try/catch?

try/catch is imperative and only works for code blocks. Error Boundaries are declarative and work for the entire component tree's rendering phase.

Is there a library to make this easier?

Yes, 'react-error-boundary' is the industry standard. It provides a functional wrapper and a 'reset' capability to let users 'Try Again'.

Does it catch API errors?

Only if the API error causes a crash during rendering. Usually, you handle API errors with state (e.g., setError(true)) and display an error message manually.

Previous

react testing

Next

react best practices

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.