Sub topic 2
Error boundaries: the idea
This chapter explains what an error boundary is and what it guarantees. It assumes you can write React function components with JSX, that you know props, state and the component lifecycle, and that you are comfortable with throw and try/catch. The next chapter covers the full class implementation. This one builds the mental model.
The problem: one throw takes down the whole page
A component's render function is supposed to compute JSX from props and state. Sometimes it throws instead. Typical causes are reading a property of undefined, calling .map on something that is not an array, or a malformed API response that the component did not expect.
React's rule for this case is strict. If an error is thrown during rendering and nothing handles it, React unmounts the entire component tree, starting from the root. The user sees a blank page. The cause is not React being fragile. React cannot know whether the UI is still consistent after a failed render, and showing corrupted UI is considered worse than showing nothing.
function Profile({ user }) {
// Throws a TypeError if user.address is undefined.
return <p>{user.address.city}</p>;
}
function App() {
return (
<div>
<Header />
<Profile user={{ name: "Ada" }} />
<Footer />
</div>
);
}Here Header and Footer are healthy. Because Profile throws, the user loses all three. Error boundaries exist to limit that loss to the part of the tree that actually failed.
What an error boundary is
An error boundary is a component that catches errors thrown while rendering anything below it in the tree. It then renders a fallback UI in place of the subtree that failed. Components outside the boundary keep working.
A boundary has three defining properties:
- It is a class component. A component becomes a boundary by defining
static getDerivedStateFromError,componentDidCatch, or both. - It protects its descendants, not itself. If the boundary's own render throws, the error moves up to the next boundary above it.
- It works like a
catchclause for the component tree. Atry/catchguards a block of imperative code. A boundary guards a region of the render tree.
The following diagram shows the effect. The error is thrown in Profile. The nearest boundary above it handles the error, and the rest of the tree is untouched.
How a boundary catches an error
React processes a render in two broad phases. In the render phase, React calls your components to work out what the UI should look like. This phase must be free of side effects. In the commit phase, React applies the result to the DOM and runs effects and lifecycle callbacks.
When a component throws during the render phase, React walks up the tree looking for the nearest boundary. If it finds one, it calls that boundary's methods, which fit into the two phases:
| Method | Phase | Purpose |
|---|---|---|
| `static getDerivedStateFromError(error)` | Render | Returns new state, so the boundary's next render can show a fallback. Must be pure. |
| `componentDidCatch(error, info)` | Commit | Runs side effects such as logging. Receives `info.componentStack`. |
Because getDerivedStateFromError runs during rendering, it must not log, send network requests or do anything else with side effects. Those belong in componentDidCatch. React then re-renders the boundary with the new state. The boundary's render method sees the error in its state and returns the fallback instead of this.props.children.
If no boundary exists anywhere above the throwing component, React reaches the root and unmounts everything. That is the blank-page behavior described at the start.
A minimal boundary
The smallest useful boundary needs only getDerivedStateFromError and a render method that chooses between the fallback and the children:
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
function Profile({ user }) {
return <p>{user.address.city}</p>;
}
export default function App() {
return (
<div>
<h1>My app</h1>
<ErrorBoundary fallback={<p>Could not show the profile.</p>}>
<Profile user={{ name: "Ada" }} />
</ErrorBoundary>
<p>This paragraph stays visible.</p>
</div>
);
}Running this shows the heading, the fallback message and the last paragraph. Profile throws a TypeError, but only its subtree is replaced.
Two details are worth noting. First, the boundary has no knowledge of the error's cause. It just flips a flag. The next chapter stores the error itself and adds componentDidCatch for logging. Second, the boundary is reusable. You pass the fallback as a prop, so the same class can guard many parts of the UI.
What happens to the failed subtree
When a boundary switches to its fallback, the children it was showing are unmounted. This has consequences you should plan for:
- Local state inside the failed subtree is lost. Form input, scroll position, expanded panels and similar state are discarded.
- Effects in the subtree run their cleanup functions, because the components are unmounting.
- Components outside the boundary keep their state. Typing in a search box in the header, for example, is unaffected by a failure in the sidebar.
The boundary does not repair the component or retry. It stays in the error state until something resets it. Resetting is covered in a later chapter. For now, treat the fallback as a stable state the user stays in.
Development versus production behavior
In development builds, React reports a caught error to the console and, in many setups, your tooling shows an error overlay even though a boundary handled it. This can look like the boundary failed. It did not. Dismiss the overlay and you will see your fallback behind it. In production builds there is no overlay, and users see only the fallback.
The console message also includes the component stack. This is a list of the components that were being rendered when the error occurred, which is far more useful for debugging than a plain JavaScript stack trace. componentDidCatch receives the same information so you can send it to a logging service.
Why there is no hook for this
You might expect a useErrorBoundary-style built-in hook in React. There isn't one. The two methods that make a component a boundary exist only on classes, and React has no function-component equivalent as of React 19. So even in a codebase that is entirely function components, the boundary itself is a class. You can write that class once and reuse it everywhere. Or you can use a library that provides it, as the chapter on react-error-boundary explains.
What a boundary is for
Boundaries answer one question: "if this part of the UI cannot render, what should the user see instead?" They are not a general-purpose error handler. Some errors never reach them, notably errors in event handlers and in asynchronous code. A later chapter lists these cases in detail and shows how to route such errors to a boundary when you want to.
A useful rule of thumb is to think of a boundary as protecting against surprises in what you render. Plan the failure modes you can predict with ordinary code. Validate input, use optional chaining where data may be absent, and handle failed requests where they happen. Keep boundaries as a safety net for the failures you did not predict.
Summary of the idea
- A render error that nothing handles unmounts the whole tree.
- A boundary is a class component that catches render errors from its descendants and shows a fallback.
getDerivedStateFromErrorruns during rendering and must be pure.componentDidCatchruns after commit and is for side effects.- The failed subtree is unmounted, so its local state is lost. Everything outside the boundary stays mounted.
- The boundary protects only what is below it. Its own errors go to the next boundary up.
Exercise
In the minimal boundary above, a developer moves a console.error(error) call into getDerivedStateFromError so that errors are logged. Why is this a poor placement, and where should the logging go?
Show answer
getDerivedStateFromError runs during the render phase, which must be free of side effects. React may call render-phase code more than once, so logging there can produce duplicate or misleading entries. Logging belongs in componentDidCatch, which runs in the commit phase and also receives info.componentStack with the component stack.
Exercise
An app has one ErrorBoundary wrapping only the Sidebar. A component inside MainContent, which is outside that boundary, throws during render. What does the user see, and why?
Show answer
The user sees a blank page. The throwing component has no boundary above it, so React walks up to the root and unmounts the entire tree, including the Sidebar. A boundary protects only its own descendants, so the one around the Sidebar does not help.
Exercise
A boundary's fallback shows a message built from this.props.fallbackMessage.toUpperCase(), but a parent forgets to pass fallbackMessage. What happens when a child throws?
Show answer
The child's error triggers the fallback render, which then throws a TypeError because fallbackMessage is undefined. A boundary cannot catch errors from its own render, so the new error moves to the next boundary above it. If there is none, the whole tree unmounts.