React / 45
Error boundaries
A class component that catches render errors in its children and shows a fallback instead of a blank page. Still the one thing you can't do with a hook.
How it works
An error boundary is a class component with one or both of these methods:
| Method | When React calls it | Its job |
|---|---|---|
static getDerivedStateFromError(error) | During rendering, right after a child throws | Return new state, e.g. { hasError: true }, so the next render shows the fallback. Must be pure. |
componentDidCatch(error, info) | In the commit phase, after the fallback is on screen | Side effects: send error and info.componentStack to a logging service. |
root
<App />
<Header />
<Menu />
<Cart /> threw
"Cart couldn't load. Try again"
Write one (once)
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Caught:", error, info.componentStack); // or your logger
}
render() {
if (this.state.hasError) {
return (
<div role="alert">
<p>{this.props.message ?? "Something went wrong."}</p>
<button onClick={() => this.setState({ hasError: false })}>Try again</button>
</div>
);
}
return this.props.children;
}
}Then wrap the risky parts:
<Header />
<Menu />
<ErrorBoundary message="Cart couldn't load.">
<Cart />
</ErrorBoundary>"Try again" clears the error, so the boundary renders its children again. If the bug is still there, it simply catches it again.
One broken widget, not a blank page
Try it<Menu />
Paneer tikka
<Cart />
2 items in your cart
- no errors yet
Where to put them
You don't wrap every component. Ask: "if this breaks, what should the user still be able to use?"
- One near the top of the app, so nothing ever ends in a blank page.
- One per independent area: a sidebar, a chart, the comments section, a lazy-loaded page. A broken chart shouldn't take the checkout with it.
- Not around tiny pieces like each avatar or button. That's noise.
What it does not catch
Error boundaries catch errors thrown while React is rendering (and in lifecycle methods and effects) of the components below them. They do not catch:
- Errors in event handlers (
onClick): React isn't rendering at that moment. Usetry/catchand put the error in state. - Async code like
setTimeoutor afetchcallback, for the same reason. - Errors thrown in the boundary itself: only a boundary higher up can catch those.
- Errors during server-side rendering.
A common trick for the first two: catch the error and store it in state, then throw it during render so the boundary sees it.
Don't
Hoping a boundary catches a click error
<button onClick={() => {
JSON.parse(badText); // throws in a handler
}}>
Import
</button>
// boundary never sees itDo
Handle it where it happens
function handleImport() {
try {
setData(JSON.parse(badText));
} catch (err) {
setError(err.message); // show it in the UI
}
}Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
