Skip to content
jshacks.dev
Frameworks

Catch render errors with an error boundary

Show a fallback instead of a blank screen when a React component throws while rendering, using a class-based error boundary or react-error-boundary.

1 min read
Summarize in AI

An error thrown while rendering unmounts the whole React tree unless something catches it. An error boundary is that something, and it still has to be a class component.

src/ErrorBoundary.jsxJSX
import { Component } from 'react';

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

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

  componentDidCatch(error, info) {
    console.error('Render failed:', error.message, info.componentStack);
  }

  render() {
    if (this.state.error) {
      return <p>Something went wrong.</p>;
    }
    return this.props.children;
  }
}
src/App.jsxJSX
import { ErrorBoundary } from './ErrorBoundary.jsx';
import { Chart } from './Chart.jsx';

export function App() {
  return (
    <ErrorBoundary>
      <Chart data={null} />
    </ErrorBoundary>
  );
}
Text
Something went wrong.

If Chart throws while rendering with null data, getDerivedStateFromError stores the error and the boundary renders the fallback in place of its children. The rest of the page stays alive. See Catching rendering errors with an error boundary.

Boundaries do not catch errors in event handlers, async code or the server. For those, handle the error where it happens. The react-error-boundary package wraps this pattern in a function component with a reset button.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.