Every component tree eventually renders something you didn't expect: a book with no title, an API field that's suddenly null, a third-party widget with a bug. This chapter is about what happens next. React's answer has three layers: error boundaries that contain a failure to one part of the screen, root error handlers that report errors to your monitoring, and Owner Stacks that make the error tell you which code caused it.
Error boundaries are the reason the class components chapter exists: they're the one feature you still have to write as a class.
The problem: one bad record blanks the page#
Here's the reading list with one malformed book. The card calls book.title.toUpperCase(), and one book has no title. Press the button.
import { useState } from "react";
import { books } from "guide-tools";
type Book = { id: number; title?: string; year: number };
function BookCard({ book }: { book: Book }) {
return (
<li>
{book.title!.toUpperCase()} <small>{book.year}</small>
</li>
);
}
export default function App() {
const [list, setList] = useState<Book[]>(books.slice(0, 4));
return (
<>
<h3>Reading list</h3>
<button onClick={() => setList((l) => [...l, { id: 99, year: 2024 }])}>Add a book with no title</button>
<ul>
{list.map((b) => (
<BookCard key={b.id} book={b} />
))}
</ul>
</>
);
}Everything disappears: the heading, the button, the four healthy books. That's deliberate. Since React 16, an error during rendering that nothing catches unmounts the whole root. The React team's reasoning: leaving a corrupted UI on screen (a checkout showing the wrong total, a message sent to the wrong person) is worse than showing nothing. But blank is rarely what you want either. You want the broken card to fail on its own.
Error boundaries#
An error boundary is a class component that defines static getDerivedStateFromError, componentDidCatch, or both. When a component below it throws while rendering, React walks up the tree to the nearest boundary, throws away the work in progress for that boundary's subtree, and renders the boundary again in its error state.
static getDerivedStateFromError(error)runs during rendering. It returns state that tellsrenderto show a fallback. Keep it pure.componentDidCatch(error, info)runs after commit. It's for side effects like logging, andinfo.componentStacktells you where in the tree the error happened.
The tree renders normally. An error boundary wraps the book list; the header sits outside it.
Here's a reusable boundary with a reset, wrapped around each card. Break a book, then try "Try again" before and after fixing it.
import { Component, type ErrorInfo, type ReactNode } from "react";
type Props = {
fallback: (error: unknown, reset: () => void) => ReactNode;
onReset?: () => void;
children: ReactNode;
};
type State = { error: unknown; hasError: boolean };
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null, hasError: false };
// Render phase: switch to the fallback. Anything can be thrown, so type it unknown.
static getDerivedStateFromError(error: unknown): State {
return { error, hasError: true };
}
// Commit phase: report it. This is where you'd call your error monitoring service.
componentDidCatch(error: unknown, info: ErrorInfo) {
console.log("componentDidCatch:", (error as Error).message);
console.log("componentStack:", info.componentStack?.trim().split("\n").slice(0, 3).join(" | "));
}
reset = () => {
this.props.onReset?.(); // let the caller fix whatever caused the error
this.setState({ error: null, hasError: false });
};
render() {
if (this.state.hasError) return this.props.fallback(this.state.error, this.reset);
return this.props.children;
}
}Three things to notice. The heading and the other three books survive, because each card has its own boundary. The console shows React's own report of the caught error alongside our componentDidCatch log (that report comes from the root's onCaughtError, covered below). And reset only works because onReset fixes the data first: resetting a boundary just renders the children again, and if the cause is still there they throw again and you're back to the fallback.
That last point is why many boundaries reset automatically when some input changes, like the book id or the route. Two easy ways: give the boundary a key tied to that input (a new key remounts it fresh), or compare "reset keys" in componentDidUpdate.
Where to put boundaries#
Granularity is a product decision. One boundary around the whole app gives you a "Something went wrong" page instead of a blank one, which is the minimum. Boundaries around independent regions (sidebar, feed, each widget on a dashboard) let the rest keep working. A boundary per list item is fine when items are independent, as here. A good rule: put a boundary wherever you'd be happy to show a fallback and keep everything else.
react-error-boundary#
You'll rarely write this class in production code. The react-error-boundary package is the common choice; it isn't in this guide's sandbox, so here it is as static code:
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
return (
<div role="alert">
<p>Couldn't load this book: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
<ErrorBoundary
FallbackComponent={Fallback}
onError={(error, info) => reportToMonitoring(error, info.componentStack)}
resetKeys={[bookId]} // reset automatically when the book changes
>
<BookDetails id={bookId} />
</ErrorBoundary>;
// Inside a child: send an error from an event handler or async code to the boundary.
function SaveButton() {
const { showBoundary } = useErrorBoundary();
return <button onClick={() => save().catch(showBoundary)}>Save</button>;
}It's the same class underneath, plus resetKeys, a FallbackComponent API and the showBoundary escape hatch for errors the boundary can't see on its own. Which brings us to those.
What boundaries catch, and what they miss#
A boundary catches errors thrown while React is working on its subtree: during rendering, in class lifecycle methods and constructors, and in effects (useEffect, useLayoutEffect) of components below it. It does not catch:
- Event handlers. A click handler runs after rendering, outside React's render and commit. If it throws, React isn't in the middle of anything to unwind; the error goes to the browser like any uncaught exception, and the UI stays as it was.
- Async code. A
setTimeoutcallback or a rejected promise runs later, on its own stack, long after the render finished. - Server rendering. Boundaries don't render fallbacks on the server. With streaming SSR, an error inside a
<Suspense>boundary makes the server send that Suspense fallback, and React retries the component on the client, where an error boundary can catch it if it fails again. See SSR and hydration. - Errors thrown by the boundary itself. A boundary catches errors from its children, not from its own
renderor fallback. If the fallback throws, the error goes to the next boundary up.
Try each button. The two that aren't caught leave the UI unchanged while the sandbox reports an uncaught error.
import { useState } from "react";
import { fakeFetch } from "guide-tools";
import { ErrorBoundary } from "./ErrorBoundary";
function Buttons() {
const [renderCrash, setRenderCrash] = useState(false);
const [, setState] = useState(0);
if (renderCrash) throw new Error("thrown during render");
return (
<>
<button onClick={() => { throw new Error("thrown in onClick"); }}>1. Throw in onClick</button>{" "}
<button onClick={() => setTimeout(() => { throw new Error("thrown in setTimeout"); }, 0)}>2. Throw in setTimeout</button>{" "}
<button onClick={() => setRenderCrash(true)}>3. Throw during render</button>{" "}
<button
onClick={() => {
fakeFetch("/missing", { delay: 100 }).catch((err: unknown) => {
// Rethrow inside a state updater: React runs it during render, so the boundary sees it.
setState(() => {
throw new Error("async error, rethrown through state: " + (err as Error).message);
});
});
}}
>
4. Async error, routed to the boundary
</button>
</>
);
}
export default function App() {
const [key, setKey] = useState(0);
return (
<ErrorBoundary
key={key}
fallback={(error) => (
<p role="alert">
Boundary caught: {(error as Error).message} <button onClick={() => setKey((k) => k + 1)}>Reset</button>
</p>
)}
>
<Buttons />
</ErrorBoundary>
);
}Button 4 shows the standard workaround for errors outside rendering: catch them yourself, then rethrow inside a state updater function. React calls the updater during the next render, so the error now happens where a boundary can catch it. showBoundary in react-error-boundary does the same thing. Note also the key on the boundary: bumping it remounts the boundary and its children from scratch, which is the bluntest reset there is.
React 19 also routes errors from Actions: if an async function passed to startTransition (or a form action) throws, React shows the nearest error boundary. That's in Actions. For event handlers, the normal answer is still the plain one: try/catch in the handler and set some error state, because an error in a click handler usually deserves a message next to the button, not a fallback replacing a region.
Reporting: root error handlers React 19#
Boundaries decide what the user sees. Separately, you want every error reported to monitoring, whether a boundary caught it or not. React 19 added three options to createRoot and hydrateRoot for that:
| Option | Called when | Default in React 19 |
|---|---|---|
onCaughtError(error, info) | An error boundary caught an error. info has componentStack and errorBoundary (the boundary instance). | console.error |
onUncaughtError(error, info) | No boundary caught it, so React unmounted the root. info has componentStack. | Rethrows to the browser via reportError |
onRecoverableError(error, info) | React hit an error it recovered from on its own, typically a hydration mismatch that it fixed by rendering on the client. | reportError |
Before React 19 there was one channel: React rethrew caught errors too (so they appeared twice in the console) and you hooked monitoring into window.onerror or componentDidCatch in every boundary. Now there's one place per kind of error, set once at the root.
The sandbox below creates its own root (script mode) so it can pass the options. It also prints both stacks for the caught error, which the next section explains.
import { captureOwnerStack, useState, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { ErrorBoundary } from "./ErrorBoundary";
const firstLines = (s: string | null | undefined, n = 4) => (s ?? "null").trim().split("\n").slice(0, n).join(" | ");
const root = createRoot(document.getElementById("root")!, {
onCaughtError(error, info) {
console.log("[onCaughtError]", (error as Error).message);
console.log(" boundary:", info.errorBoundary?.constructor.name);
console.log(" component stack:", firstLines(info.componentStack));
// Development only: captureOwnerStack is missing from production builds, so guard it.
console.log(" owner stack:", typeof captureOwnerStack === "function" ? firstLines(captureOwnerStack()) : "(production build)");
},
onUncaughtError(error, info) {
console.log("[onUncaughtError]", (error as Error).message);
console.log(" component stack:", firstLines(info.componentStack));
},
onRecoverableError(error) {
console.log("[onRecoverableError]", (error as Error).message);
},
});
function Price({ cents }: { cents?: number }) {
return <strong>${cents!.toFixed(2)}</strong>;
}
function Panel({ children }: { children: ReactNode }) {
return (
<section>
<fieldset>{children}</fieldset>
</section>
);
}
function App() {
const [inside, setInside] = useState(false);
const [outside, setOutside] = useState(false);
return (
<>
<button onClick={() => setInside(true)}>Break inside a boundary</button>{" "}
<button onClick={() => setOutside(true)}>Break outside any boundary</button>
<ErrorBoundary fallback={<p role="alert">This panel failed.</p>}>
<Panel>{inside ? <Price /> : <Price cents={1999} />}</Panel>
</ErrorBoundary>
{outside ? <Price /> : null}
</>
);
}
root.render(<App />);"Break inside" calls onCaughtError and the panel shows its fallback. "Break outside" calls onUncaughtError and the whole root unmounts. Because these handlers replace the defaults, nothing is rethrown to the browser; in a real app you'd send both to your monitoring service.
onRecoverableError fires when React recovers by itself. The most common case is hydration: the server's HTML doesn't match what the client renders, so React throws away the server HTML for that part and renders on the client. Here the "server" and "client" disagree on purpose:
<div id="root"></div>
The page ends up correct ("client"), but the mismatch is a real bug: React had to discard server work. SSR and hydration covers why mismatches happen and how to avoid them.
Owner Stacks React 19.1#
A component stack answers "where in the tree did this fail?" It lists every ancestor from the failing component up to the root: your components, the wrapper components that only pass children through, and in React's format, DOM elements like fieldset too. In a big app that's a long list, and the component that actually created the broken element is somewhere in the middle.
An Owner Stack answers a different question: "which code made this element?" The owner of an element is the component whose render wrote the JSX for it. In the sandbox above, <Price /> sits inside fieldset, section and Panel, but App is the component that wrote <Price /> without cents. Owner Stacks skip parents that only passed the element through, so they point at the code that's actually responsible. React DevTools and React's own development error messages use them since 19.1.
You can read the current one with captureOwnerStack(), exported from react:
- It returns a string, or
nullwhen called outside a React-controlled context (asetTimeoutorfetchcallback, for example). - It works during render, in effects, in React event handlers, and in the root error handlers above.
- It's development only. In production builds
captureOwnerStackisn't exported at all, so code that runs in both must guard it:import * as React from "react"and checkprocess.env.NODE_ENV !== "production"before callingReact.captureOwnerStack().
A typical use is enriching your own development error overlay or logs: call it from a patched console.error or from onCaughtError, and show it next to the message. Owner Stacks are a debugging tool, not monitoring data: production error reports still rely on componentStack and source maps.
Pitfalls#
Check your understanding#
One book in this list has no title. Right now the whole list is replaced by the fallback. Change App so only the broken book shows the fallback and the others still render. Don't change ErrorBoundary or BookCard. Press Check.
import { ErrorBoundary } from "./ErrorBoundary";
type Book = { id: number; title?: string };
const list: Book[] = [
{ id: 1, title: "Refactoring" },
{ id: 2 },
{ id: 3, title: "Thinking in Systems" },
];
function BookCard({ book }: { book: Book }) {
return <span>{book.title!.toUpperCase()}</span>;
}
export default function App() {
return (
<>
<h3>Reading list</h3>
<ErrorBoundary fallback={<span role="alert">Couldn't show this book</span>}>
<ul>
{list.map((b) => (
<li key={b.id}>
<BookCard book={b} />
</li>
))}
</ul>
</ErrorBoundary>
</>
);
}A component inside an error boundary has <button onClick={() => JSON.parse("{bad")}>Load</button>. The user clicks it. What does the user see, and which root error handler runs?
Which error does an error boundary catch?
An interviewer asks: "What is an error boundary, what does it catch, and how would you handle errors in a production React app?"
Interview angle
Since React 16, an uncaught render error unmounts the whole root, because a corrupted UI is worse than none. Error boundaries contain the damage: a class with getDerivedStateFromError renders a fallback for its subtree and componentDidCatch logs. They catch errors in render, lifecycle methods and effects below them, but not in event handlers, async code, server rendering or the boundary itself. React 19 adds root options, onCaughtError, onUncaughtError and onRecoverableError, to report every error from one place, and 19.1 adds Owner Stacks, a development-only trace of which components created the failing element.
What does an error boundary catch, and what doesn't it catch?
Why are error boundaries still class components?
What happens when a render error isn't caught by any boundary?
What are onCaughtError, onUncaughtError and onRecoverableError?
How do you decide where to put error boundaries, and how do you recover from an error?
What's an Owner Stack, and how is it different from a component stack?
Recap#
- An uncaught render error unmounts the whole root. Error boundaries contain failures: classes with
getDerivedStateFromError(show a fallback) andcomponentDidCatch(log). - Boundaries catch errors during render, lifecycle methods and effects below them. They miss event handlers, async code, server rendering and their own errors; route those deliberately or handle them locally.
- Resetting a boundary re-renders its children, so fix the cause first or reset by
keyor reset keys.react-error-boundarypackages all of this. - React 19 root options report errors in one place:
onCaughtError,onUncaughtErrorandonRecoverableError. - Owner Stacks (19.1) show which components created the failing element.
captureOwnerStackis development only and must be guarded.
Sources#
- react.dev: Catching rendering errors with an error boundary
- react.dev: createRoot options and hydrateRoot options
- react.dev: React 19: better error reporting
- react.dev: captureOwnerStack
- React changelog, 19.1.0: Owner Stacks
- react-error-boundary on GitHub
- Facts checked November 24, 2026.