Sub topic 3
Writing a class-based error boundary
This chapter assumes you can write React function components and JSX, and that you know basic class syntax (extends, static, this). You should also have seen the idea of an error boundary from the previous chapter. Here you write one by hand and learn what each part does.
Why a class
React gives a component the power to catch rendering errors through two lifecycle methods: static getDerivedStateFromError and componentDidCatch. Both exist only on class components. There is no hook that does the same job. A codebase made entirely of function components therefore still needs one small class, either written by you or imported from a library. Later chapters cover that library. Writing the class yourself first shows you what the library does.
A component becomes an error boundary when it defines at least one of the two methods. The usual practice is to define both, because they do different jobs.
The 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 class has four parts. Each one has a narrow responsibility.
state = { error: null }is the initial state.nullmeans "no error yet".getDerivedStateFromErrorturns a thrown error into a state update.componentDidCatchis where side effects such as logging go.renderchooses between the children and the fallback.
You use the boundary by wrapping the 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 while rendering, only that subtree is replaced by the fallback. Components outside the boundary keep running.
What happens when a child throws
The order of events matters, because it explains why the two methods have different rules.
React discards the half-finished work for the failed subtree. It looks up the component tree for the nearest ancestor that defines one of the two methods. It then calls getDerivedStateFromError on that ancestor, and the ancestor renders again with the returned state. Only after the fallback is on screen does React call componentDidCatch.
If no ancestor is a boundary, React unmounts the whole tree. The user sees a blank page. Placing boundaries is the way to avoid that outcome, and a later chapter covers it.
The two methods compared
| Row | `getDerivedStateFromError` | `componentDidCatch` |
|---|---|---|
| Runs in | Render phase | Commit phase |
| Receives | `error` | `error`, `info` |
| Purpose | Update state so the next render shows the fallback | Side effects: logging, reporting |
| Must be pure | Yes | No |
| Has `this` | No, it is static | Yes |
| Can call `setState` | No, it returns a state object instead | Technically yes, but avoid it |
getDerivedStateFromError
This method is static, so it cannot read this.props or call instance methods. It receives the thrown value and returns an object that React merges into state, the same way setState merges.
Because it runs during the render phase, React may call it more than once for the same error, and it must have no side effects. Do not log, send network requests, or touch the DOM here. Return state and nothing else.
componentDidCatch
This method runs after the fallback is committed, so side effects are safe. The second argument, info, has a componentStack string. It lists the components between the one that threw and the boundary, which is far more useful in a log than the JavaScript stack alone. A later chapter covers reporting in detail. For now, console.error is enough.
Calling setState inside componentDidCatch to show the fallback is the older pattern from before getDerivedStateFromError existed. React warns about a boundary that relies on it, so keep state updates in the static method.
Reading the render method
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}The render method is the only place that decides what the user sees. Two behaviors follow from it.
- While
errorisnull, the boundary is invisible. It returnschildrenunchanged and adds no DOM element of its own. - Once
erroris set, the boundary stops rendering its children. The children are unmounted, and any state they held is lost.
Nothing in this class ever sets error back to null. After a failure, the boundary shows the fallback until the boundary itself unmounts. Letting users retry is a separate topic, covered in the chapter on recovery.
Edge cases in the minimal version
A thrown value can be falsy
JavaScript lets you throw anything, including undefined or null. Suppose some code runs throw undefined. Then getDerivedStateFromError returns { error: undefined }, and if (this.state.error) is false. The boundary renders its children again, they throw again, and you get a loop of failures with no fallback. Rare, but real, especially with third-party code. A boolean flag avoids it:
import { Component } from "react";
class SafeErrorBoundary extends Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
console.error(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}The fallback can throw
A boundary catches errors from its children, not from itself. If the fallback element throws while rendering, the error moves up to the next boundary above. If there is none, the tree unmounts. Keep fallbacks simple: plain text and static markup, with no data fetching and no dependence on the state that just failed.
The boundary must be above the failure
A boundary never catches an error thrown by its own render. Putting <ErrorBoundary> inside the component that throws does nothing. The boundary has to be an ancestor of the failing component:
// Does not help: Profile throws before ErrorBoundary is ever rendered.
function Profile({ user }) {
return (
<ErrorBoundary fallback={<p>Oops</p>}>
<p>{user.name.first}</p>
</ErrorBoundary>
);
}If user is undefined, the expression user.name.first throws while Profile renders. The ErrorBoundary element is created inside that same render, so it never mounts. Move the boundary to the parent that renders Profile, as in the App example earlier.
Do not do work in the static method
The next snippet looks harmless, but it breaks the rules for the render phase:
static getDerivedStateFromError(error) {
sendToLoggingService(error); // wrong: side effect in the render phase
return { error };
}React can call this method several times for one error, so the service may receive duplicates. In development with Strict Mode, rendering can also be repeated on purpose to expose this kind of bug. Put the call in componentDidCatch.
Making the boundary flexible
The fallback prop in the minimal class accepts one element. Two small changes make the boundary more useful without growing the code much. Your fallback can be a function that receives the error, and the boundary can accept an onError callback for reporting:
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
render() {
if (this.state.hasError) {
const { fallback } = this.props;
return typeof fallback === "function"
? fallback(this.state.error)
: fallback;
}
return this.props.children;
}
}
function App() {
return (
<ErrorBoundary
fallback={(error) => <p>Failed to load: {error.message}</p>}
onError={(error, info) => console.error(error, info.componentStack)}
>
<Profile />
</ErrorBoundary>
);
}Now one class serves many places with different messages and different reporting, and nothing is hard-coded in the boundary. This is also the shape the react-error-boundary library generalizes, as a later chapter shows.
Common mistakes
- Defining only
componentDidCatch. The boundary has no clean way to show a fallback, and React warns. Always includegetDerivedStateFromError. - Using a function component. Function components cannot be boundaries. The error goes to the nearest class boundary above, or unmounts the tree.
- Placing the boundary inside the failing component. It must wrap the component from outside.
- Forgetting to render
childrenin the happy path. A boundary that returnsnullwhen there is no error hides the whole subtree. This is easy to miss in a refactor. - Doing side effects in
getDerivedStateFromError. Move them tocomponentDidCatch.
Error boundaries also leave some errors uncaught: event handlers, asynchronous code, and server rendering. That limit is the subject of the next chapter. Until then, assume this class handles only errors thrown while React is rendering, in lifecycle methods, and in constructors of components below it.
Exercise
A developer writes an ErrorBoundary class with only componentDidCatch, which calls this.setState({ error }) and logs the error. A second developer says the boundary should use getDerivedStateFromError instead, and also moves the logging call into it. Which of these two changes is correct, and which is a mistake?
Show answer
Adding getDerivedStateFromError to return { error } is correct. It is the supported way to switch to the fallback, it runs in the render phase, and React does not warn about it. Moving the logging call into it is a mistake. That method runs in the render phase, must be pure, and may be called more than once for one error, so logging there can produce duplicates. Logging belongs in componentDidCatch, which runs once after the fallback is committed.
Exercise
This component is meant to be protected by a boundary. Why does the boundary fail to help when user is undefined, and how do you fix it? function Profile({ user }) { return ( <ErrorBoundary fallback={<p>Oops</p>}> <p>{user.name}</p> </ErrorBoundary> ); }
Show answer
The expression user.name throws while Profile itself is rendering, before the ErrorBoundary element is ever mounted. A boundary only catches errors from components below it, never from the component that renders it. The fix is to move the boundary to the parent, wrapping <Profile user={user} />, so that Profile is a descendant of a mounted boundary.