Lesson 21 of 37Modern React
Error Boundaries and Resilient UI
Stop one broken widget from blanking the whole app: what error boundaries catch, where to place them, how to reset them, and how to report errors.
A support ticket arrives with a screenshot of a completely white page. The cause turns out to be one optional field: the API started returning null for a promo banner's price, and price.amount.toFixed(2) threw while rendering. Since React 16, an error thrown during rendering that nothing catches unmounts the whole app, because React would rather show nothing than a half-broken screen that might, say, display the wrong account balance. Error boundaries are how you decide which parts of the screen are allowed to fail on their own. Getting them right is the difference between "the banner is missing" and "the site is down".
What a boundary catches, and what it does not
An error boundary is a component that catches errors thrown by the components below it in the tree while React is working on them, and shows a fallback instead of that subtree. "While React is working on them" is the key phrase. A boundary catches errors thrown:
- while rendering a component (the
toFixedcrash above), - in lifecycle methods of class components and in effects (
useEffect,useLayoutEffect) and ref callbacks, - when a promise passed to
use()rejects, as you saw in Data Fetching, - when an Action passed to
startTransitionor a form'sactionthrows (from Actions and Optimistic UI).
It does not catch errors thrown:
- in event handlers. A click handler runs after rendering is done, outside React's render work. The error goes to the browser like any other.
- in async code you schedule yourself:
setTimeout, a.thencallback, anawaitinside a plain async function that is not an Action. - in the boundary itself. If the fallback throws, the error goes to the next boundary up.
- during server rendering. With streaming SSR, an error on the server makes React send the nearest Suspense fallback in the HTML and try that part again in the browser. If it fails again there, the client-side boundary catches it.
The event handler rule surprises people, but the reasoning is simple: when a handler throws, the screen is still in a consistent state, so React has no reason to replace UI. You handle those errors yourself with try/catch and an error state, or forward them to a boundary on purpose (shown below).
<Dashboard /> catch? Pick all that apply.None picked yet
The class API
There is still no hook for this. A boundary is a class component that implements one or both of two methods:
static getDerivedStateFromError(error)runs during the render phase. It must be pure: return the new state (usually{ error }) so the next render shows the fallback.componentDidCatch(error, info)runs during the commit phase, after the fallback is on screen. This is where side effects such as reporting go.info.componentStacktells you which components the error passed through, which is far more useful in a bug report than the JavaScript stack alone.
The demo has a widget inside a boundary and a counter outside it. Try the three buttons. "Break render" sets the price to null and the next render crashes. "Throw in handler" throws from a click handler: nothing on screen changes, and the error only reaches the browser's console. "Forward handler error" catches the same kind of error and re-throws it during a render, where the boundary can see it. The counter outside keeps working the whole time.
Two things to notice. First, the useThrowToBoundary trick works because a state updater function runs during the next render; throwing inside it turns a handler error into a render error. react-error-boundary packages this as showBoundary. Second, "Try again" clears the boundary's state, which remounts the children. The widget comes back with its initial state, not the null that crashed it. Resetting only helps if the remounted tree will not hit the same problem again.
In development, React shows caught errors in the console with their component stack, and frameworks such as Next.js add an overlay on top. Production builds do neither, so if you do not report errors yourself, you will not hear about them.
react-error-boundary in practice
Most teams do not write the class by hand. The small react-error-boundary package wraps it with the features you would add anyway:
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
import type { FallbackProps } from "react-error-boundary";
function WidgetFallback({ resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
<p>This panel could not load.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export function OrdersPanel({ customerId }: { customerId: string }) {
return (
<ErrorBoundary
FallbackComponent={WidgetFallback}
onError={(error, info) => reportError(error, info.componentStack)}
onReset={() => queryClient.resetQueries({ queryKey: ["orders", customerId] })}
resetKeys={[customerId]}
>
<Orders customerId={customerId} />
</ErrorBoundary>
);
}
function ExportButton() {
const { showBoundary } = useErrorBoundary();
async function handleExport() {
try {
await exportCsv();
} catch (error) {
showBoundary(error); // hand an async error to the nearest boundary
}
}
return <button onClick={handleExport}>Export</button>;
}FallbackComponent(orfallbackRender, or a plainfallbackelement) receives theerrorand aresetErrorBoundaryfunction.onErroris yourcomponentDidCatch: report from here.onResetruns when the boundary resets, which is your chance to clear whatever caused the failure.resetKeysresets the boundary automatically when any value in the array changes. Switching to another customer clears an error that belonged to the previous one.useErrorBoundary().showBoundary(error)is the supported version of the forwarding trick, for errors from handlers and async code.
Check the package's README for the version you install; the API above has been stable for years, but details such as how error is typed have changed between major versions.
Resetting without hitting the same wall
A retry button that brings back the same error is worse than no button. Before you reset, remove the cause. With hand-made caches this is easy to forget. If a component reads use(loadProfile(id)) from a Map cache and the request fails, the rejected promise stays in the cache. Reset the boundary and the component reads the same rejected promise and fails instantly.
Untick the checkbox, wait for the first load to fail, and press Retry: the error comes straight back. Tick it and retry: the cache entry is deleted, a new request goes out, and the second attempt succeeds.
Data libraries give you the same hook in a cleaner form. TanStack Query has QueryErrorResetBoundary and resetQueries for this, and Next.js passes a reset function to its error files. The idea is the same in all of them: reset the data, then reset the boundary.
There are three ways to reset, and each fits a different moment:
- A retry button in the fallback (
resetErrorBoundary) for transient failures such as a timeout. resetKeysfor "the inputs changed, the old error no longer applies", like a new customer id.- A
keyon the boundary, such as<ErrorBoundary key={pathname}>. A new key throws away the whole subtree and mounts a fresh boundary. It is the bluntest tool: everything inside loses its state. That is usually what you want on navigation, and rarely what you want inside a form.
The first request fails and the fallback shows. The user clicks Retry. The second request would succeed. What does the user see after clicking?
const cache = new Map();
function getUser(id) {
if (!cache.has(id)) cache.set(id, fetchUser(id)); // first call rejects
return cache.get(id);
}
function User({ id }) {
const user = use(getUser(id));
return <p>{user.name}</p>;
}
<ErrorBoundary FallbackComponent={RetryFallback}> {/* Retry only calls resetErrorBoundary */}
<Suspense fallback={<p>Loading...</p>}>
<User id="7" />
</Suspense>
</ErrorBoundary>Where to put boundaries
A boundary's fallback replaces everything inside it, so placement is a product decision: what is the largest piece of the screen that can disappear while the rest stays useful?
The chart library throws on unexpected data. Its widget boundary catches it and shows 'Chart unavailable' in the same space. The rest of the page is untouched.
Some rules of thumb:
- Always have a root boundary. Otherwise one bug means a white screen.
- One per route or layout section keeps navigation alive. This is exactly what Next.js
error.tsxfiles give you per route segment (see the App Router Routing lesson). - One per independent widget, especially anything with third-party code or optional data: charts, embeds, recommendation rails, ads.
- Not one per component. Fifty boundaries means fifty fallbacks to design and test, and a user facing a page full of little "failed" boxes.
Pairing with Suspense
Loading and failure are the two non-happy states of the same piece of UI, so put their boundaries together. The usual order is the error boundary outside the Suspense boundary:
<ErrorBoundary FallbackComponent={PanelError}>
<Suspense fallback={<PanelSkeleton />}>
<Panel />
</Suspense>
</ErrorBoundary>The skeleton covers "still loading", the error fallback covers "failed", and both occupy the same area. Make them the same size as the real panel so the layout does not jump in either case.
A child of a boundary throws during render. Put React's steps in order.
- Tap the steps below in the right order.
Reporting: root options and services
A boundary shows the user something sensible. You also need to know it happened. React 19 added three options to createRoot (and hydrateRoot) that see every error in one place:
import { createRoot } from "react-dom/client";
createRoot(document.getElementById("root")!, {
// Caught by a boundary: the user saw a fallback.
onCaughtError(error, errorInfo) {
report(error, { level: "error", componentStack: errorInfo.componentStack });
},
// Not caught: React unmounted the whole app.
onUncaughtError(error, errorInfo) {
report(error, { level: "fatal", componentStack: errorInfo.componentStack });
},
// React recovered by itself, for example by re-rendering on the client after a hydration error.
onRecoverableError(error, errorInfo) {
report(error, { level: "warning", componentStack: errorInfo.componentStack });
},
}).render(<App />);Without these options React's defaults apply: caught errors go to console.error and uncaught errors go to window.reportError. Recoverable errors deserve attention even though users see nothing: a steady stream of hydration errors means the server and client disagree, and every one costs a client re-render.
Error services plug in here. Sentry's React SDK, for example, provides a handler you pass to these three options, plus its own ErrorBoundary component; check its current docs for the exact setup. Whatever you use, make sure of three things: source maps are uploaded so stacks point at your code instead of minified bundles, each event carries the release version so you can tell whether a deploy caused a spike, and no personal data (emails, tokens, form contents) ends up in the report. For errors that never touch React (a failing setTimeout, an unhandled promise rejection), the service's global error and unhandledrejection listeners are your safety net.
Fallbacks users can live with
The fallback is UI, and it deserves the same care as the happy path:
- Say what failed in plain words. "Your orders could not load" beats "Something went wrong".
- Do not show
error.messagein production. It can leak internals (SQL fragments, internal URLs) and means nothing to users. Show a short reference id instead, and log the same id with the report so support can find it. - Offer a way forward: retry for transient failures, a link home or a reload for fatal ones.
- Keep the space. A fallback the same size as the widget avoids layout shift.
- Announce it.
role="alert"makes screen readers read the message out when it appears. - Test it. Throw on purpose in a test or a dev-only toggle, so the fallback is not first rendered in production.
Match each tool to the job it does.
- error boundary
- A component that catches errors thrown while rendering, committing or running effects in its subtree and shows a fallback instead.
- getDerivedStateFromError
- Static class method called in the render phase with the error. It returns new state so the boundary renders its fallback.
- componentDidCatch
- Class method called in the commit phase with the error and
info.componentStack. The place for reporting. - component stack
- The chain of components an error passed through, such as
PriceWidgetinsideReportsPage. More useful than the JS stack for UI bugs. - resetKeys
- A
react-error-boundaryprop: when any value in the array changes, the boundary clears its error and remounts its children. - onCaughtError / onUncaughtError
- React 19
createRootoptions called for errors caught by a boundary and for errors that unmounted the app. - recoverable error
- An error React handled by itself, such as falling back to client rendering after a hydration mismatch. Reported via
onRecoverableError.