Error boundaries
Why error boundaries must still be class components, what render-time errors they catch (and what they don't), and the react-error-boundary library.
Error boundaries
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An error boundary catches a JavaScript error thrown during rendering anywhere in its child tree and renders a fallback UI instead of unmounting the whole app.
- There is no hook equivalent of an error boundary. The two lifecycle methods it needs, `static getDerivedStateFromError` and `componentDidCatch`, only exist on class components, so a boundary is one of the few places React still requires a class.
- Error boundaries catch errors in rendering, in lifecycle methods, and in constructors of components below them — but not errors in event handlers, not errors in asynchronous code like a `setTimeout` or a rejected fetch promise, and not errors in the boundary component itself.
- Because event handlers and async code fall outside their reach, a boundary is not a replacement for try/catch around a click handler or a `.catch()` on a promise; it is a safety net for the one category those don't cover.
- In practice almost nobody hand-writes the class boilerplate per feature; the `react-error-boundary` library wraps it in an `<ErrorBoundary fallback={...}>` component so the rest of the app can stay in function-component style.
- Suspense and error boundaries divide the same problem in half: Suspense's fallback covers 'still waiting,' and an error boundary's fallback covers 'failed' — a data-fetching component typically sits inside both.
Why your whole app goes blank
Without an error boundary, a render-time error anywhere in the component tree unmounts the entire application. React’s default behavior as of React 18 is to tear the whole tree down rather than leave it in a half-rendered, possibly inconsistent state — one broken card in a product grid can blank the entire page.
function ProductCard({ product }) {
// if product is null, this throws during render
return <h3>{product.name.toUpperCase()}</h3>;
}
If product turns out to be null because of a bad API response, that .name access throws during render, and with nothing catching it, the user sees a blank screen instead of a broken card. An error boundary exists to contain that failure to the part of the tree where it happened.
The one place React still needs a class
React’s hooks replaced almost every reason to write a class component — state, lifecycle effects, refs all have function equivalents. Error boundaries are the exception, because the mechanism React uses to intercept a child’s render error is built entirely on two class lifecycle methods that have no hook form:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
// runs during render, after a descendant has thrown
return { hasError: true };
}
componentDidCatch(error, info) {
// runs after render, for logging/reporting
logErrorToService(error, info.componentStack);
}
render() {
if (this.state.hasError) return this.props.fallback;
return this.props.children;
}
}
getDerivedStateFromError runs during the render phase and decides what fallback state to show; componentDidCatch runs afterward and is where you’d report the error to a logging service. Neither has ever been given a useX equivalent, so writing a boundary from scratch means writing a class, even in a codebase that otherwise never does.
What it catches, and what it deliberately doesn’t
An error boundary only catches errors that occur during React’s render pass below it: errors thrown while rendering, in a lifecycle method, or in a constructor. It does not catch:
- Errors inside event handlers (
onClick,onChange, and so on) — these run outside the render pass entirely. - Errors inside asynchronous code — a
setTimeoutcallback, a.then(), anasyncfunction body — because by the time those run, the render that scheduled them has already finished and the boundary is no longer “listening.” - Errors thrown by the boundary component itself, rather than by its children.
- Server-side rendering errors (though React 19 improved how these surface).
That split matters in practice: a data-fetching call inside useEffect that rejects needs its own .catch(), and a form submit handler that throws needs its own try/catch. Error boundaries exist specifically for the category those two patterns don’t cover — an unexpected shape of data breaking a render, a third-party component throwing on bad props, a bug in your own JSX logic.
react-error-boundary: how apps actually use it
Almost nobody repeats the class boilerplate per feature. The react-error-boundary library packages the same mechanism behind a function-component-friendly API:
import { ErrorBoundary } from "react-error-boundary";
function ProductGrid({ products }) {
return (
<ErrorBoundary
fallback={<p>Something went wrong loading this product.</p>}
onError={(error, info) => logErrorToService(error, info)}
>
{products.map((p) => (
<ProductCard key={p.id} product={p} />
))}
</ErrorBoundary>
);
}
It also supports fallbackRender for a fallback that needs access to the caught error and a resetErrorBoundary function, plus a resetKeys prop that automatically re-renders the children (giving them a fresh chance) when a value like a route param changes — useful for “try again after the user navigates” without wiring that up by hand.
Pairing with Suspense
The previous lesson’s <Suspense> boundary and an error boundary solve adjacent problems, and a data-fetching component typically sits inside both:
<ErrorBoundary fallback={<p>Couldn't load this product.</p>}>
<Suspense fallback={<Spinner />}>
<ProductDetails id={id} />
</Suspense>
</ErrorBoundary>
Suspense’s fallback covers “the request is still pending”; the error boundary’s fallback covers “the request (or anything else in render) failed.” A component built with useSuspenseQuery naturally produces both outcomes — a thrown promise while pending, a thrown error on failure — so it needs a boundary above it for each.
What the video covers
Dave Gray builds a real app over the course of the video and, from 13:10 onward, dedicates clear sections to why error boundaries are needed, installing react-error-boundary, adding a basic boundary, and then improving it into “a better error boundary” at 16:53 — the practical library workflow this lesson calls for, rather than just the bare mechanics. The segment before 13:10 covers Suspense/SWR setup for the same app and is outside this lesson’s scope; if you want the bare class-component mechanics (componentDidCatch/getDerivedStateFromError) in isolation, the Web Dev Simplified link below covers just that in under seven minutes.
Where this fits
With pending and failure states both covered, the next lesson zooms out from a single boundary to React’s rendering model itself: concurrent rendering and transitions.
Check yourself
Why can't an error boundary be written as a function component with hooks?
Catching a render error requires `static getDerivedStateFromError` (to compute fallback state) and `componentDidCatch` (to log the error), and React has never added a hook that gives a function component the same ability to intercept an error thrown by its own children during render. These two methods only exist on the class component API, so a boundary stays a class.
A button's onClick handler throws an error. Will the error boundary wrapping that button catch it?
No. Error boundaries only catch errors thrown during rendering, in lifecycle methods, or in constructors. An error thrown inside an event handler happens outside React's render pass entirely, so it propagates like a normal JavaScript error and must be handled with a regular try/catch in the handler itself.
What does the react-error-boundary library add on top of writing the class yourself?
It provides a ready-made `<ErrorBoundary>` component with a `fallback` or `fallbackRender` prop and a `resetKeys`/`onReset` mechanism for retrying, so a team gets a tested, composable error boundary without writing `getDerivedStateFromError` and `componentDidCatch` by hand in every feature that needs one.
Can an error boundary catch an error thrown by an async function called inside a useEffect?
No. That error happens asynchronously, after the render that triggered the effect has already completed, which is outside the window an error boundary watches. It needs to be caught where it actually throws, typically with a try/catch inside the async function or a .catch() on its promise.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.