Sub topic 3
Writing a class-based error boundary
This chapter assumes you can write React function components and JSX, know props and state, and are comfortable with throw and try/catch. You don't need to know class components in depth. The chapter covers only the parts a boundary uses.
Why a class
An error boundary is a component that catches errors thrown while rendering its children. React exposes this through two class lifecycle methods, getDerivedStateFromError and componentDidCatch. Function components have no equivalent hook, so a boundary you write yourself must be a class. You can still use it anywhere in a tree of function components.
The two methods
The methods run at different times and have different jobs.
| Method | Phase | Purpose |
|---|---|---|
| `static getDerivedStateFromError(error)` | Render | Return new state so the next render shows a fallback. |
| `componentDidCatch(error, info)` | Commit | Run side effects such as logging. `info.componentStack` lists the components between the error and the boundary. |
Keep the split clear. getDerivedStateFromError must be pure, because React may call it during rendering. Do your logging in componentDidCatch.
A minimal boundary
import { Component } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error(error, info.componentStack);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}The component stores the caught error in state.error. While error is null, render returns this.props.children and the boundary is invisible. Once an error is stored, render returns the fallback prop instead.
Using it
Wrap any subtree you want to protect.
function App() {
return (
<ErrorBoundary fallback={<p>Something went wrong.</p>}>
<Profile />
</ErrorBoundary>
);
}If Profile or any component below it throws during rendering, only that subtree is replaced by the fallback. Components outside the boundary keep working.
What happens step by step
Without a boundary, the same error would unmount the entire React tree and leave a blank page. The boundary limits the damage to its own subtree.
Common mistakes
- Putting the boundary inside the component that throws. A boundary catches errors from its children, not from itself. If the component that throws renders the boundary, the error passes above it. Place the boundary higher in the tree.
- Forgetting to return state. If
getDerivedStateFromErrorreturns nothing, no state changes, and the fallback never appears. - Doing side effects in
getDerivedStateFromError. Logging or network calls belong incomponentDidCatch. - Testing with a falsy error. The check
if (this.state.error)assumes the thrown value is truthy. Code can throw0or"", though it's rare. If that matters to you, store a separate flag such ashasError: true. - Expecting it to catch everything. Event handlers and asynchronous code are not covered. A later chapter covers these limits and how to route such errors to a boundary.
Try it
Add this component inside a boundary and watch the fallback replace it.
function Bomb() {
throw new Error("Boom");
}
function Demo() {
return (
<ErrorBoundary fallback={<p>Caught it.</p>}>
<Bomb />
</ErrorBoundary>
);
}Exercise
A boundary component renders <Profile /> and also contains the code that throws while rendering, in its own render method. Will the boundary show its fallback? What should you change?
Show answer
No. A boundary catches errors from components below it, not from its own render. Move the throwing code into a child component, or wrap the boundary in another boundary higher up the tree.
Exercise
Which method should send the error and info.componentStack to a logging service, and why not the other one?
Show answer
componentDidCatch. It runs in the commit phase, where side effects are allowed. getDerivedStateFromError runs during rendering and must stay pure, so it should only return new state.