React Foundations · Composition

Catching render errors

Error boundaries

Catching render errors

One component throws while rendering, and React unmounts the whole tree. The screen goes blank, and every sibling disappears with it. An error boundary catches that error and shows a fallback instead.

An error boundary is a class component that defines static getDerivedStateFromError:

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

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

  render() {
    if (this.state.hasError) {
      return <p>Something went wrong</p>;
    }
    return this.props.children;
  }
}

When a descendant throws during render, React calls getDerivedStateFromError, which returns the new state. The boundary re-renders and shows the fallback. Wrap the risky subtree in it:

<ErrorBoundary>
  <Boom />
</ErrorBoundary>

Only errors thrown during rendering are caught — not in event handlers or async code. There is no hook equivalent; error boundaries are still classes.

Your job is to wrap a throwing child in an error boundary that shows a fallback.

Challenge

A child that throws during render takes the whole screen down with it. Export an App component from App.jsx that renders a child which throws during render, wrapped in an error boundary that shows the fallback Something went wrong.

The Test renders your component and looks for that fallback paragraph. The starter renders a placeholder and no boundary, so the Test fails. Add the boundary around the child.

App.jsx
export function App() {
  return <p>All good</p>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.