Skip to content

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.

17 min read0/4 questions

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 toFixed crash 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 startTransition or a form's action throws (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 .then callback, an await inside 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).

Quick checkPick all that apply
Which errors will an error boundary around <Dashboard /> catch? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

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.componentStack tells 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.

ReactBoundaryBasics.tsx
import { Component, useState } from "react";import type { ErrorInfo, ReactNode } from "react"; type Props = { fallback: (reset: () => void) => ReactNode; children: ReactNode }; class ErrorBoundary extends Component<Props, { error: Error | null }> { state = { error: null as Error | null }; // Render phase: must be pure. Turn the error into state. static getDerivedStateFromError(error: Error) { return { error }; } // Commit phase: side effects such as reporting are allowed here. componentDidCatch(error: Error, info: ErrorInfo) { const where = info.componentStack?.match(/at (\w+)/)?.[1] ?? "unknown"; console.log(`report: "${error.message}" in ${where}`); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.reset); return this.props.children; }} // Re-throws an error during render, where a boundary can catch it.function useThrowToBoundary() { const [, setState] = useState(0); return (error: Error) => setState(() => { throw error; });} function PriceWidget() { const [price, setPrice] = useState<{ amount: number } | null>({ amount: 42 }); const throwToBoundary = useThrowToBoundary(); function handleSync() { throw new Error("Sync failed in a click handler"); // no boundary sees this } function handleSyncForwarded() { try { throw new Error("Sync failed, forwarded to the boundary"); } catch (e) { throwToBoundary(e as Error); } } return ( <div style={{ border: "1px solid #ccc", padding: 8 }}> <p>Price: {price!.amount.toFixed(2)}</p> <button onClick={() => setPrice(null)}>Break render</button>{" "} <button onClick={handleSync}>Throw in handler</button>{" "} <button onClick={handleSyncForwarded}>Forward handler error</button> </div> );} export default function App() { const [clicks, setClicks] = useState(0); return ( <div> <p> Outside the boundary: <button onClick={() => setClicks(clicks + 1)}>Clicked {clicks} times</button> </p> <ErrorBoundary fallback={(reset) => ( <div role="alert" style={{ border: "1px solid crimson", padding: 8 }}> <p>The price widget failed to load.</p> <button onClick={reset}>Try again</button> </div> )} > <PriceWidget /> </ErrorBoundary> </div> );}

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:

components/WidgetBoundary.tsx
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 (or fallbackRender, or a plain fallback element) receives the error and a resetErrorBoundary function.
  • onError is your componentDidCatch: report from here.
  • onReset runs when the boundary resets, which is your chance to clear whatever caused the failure.
  • resetKeys resets 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.

ReactRetryWithCache.tsx
import { Component, Suspense, use, useState } from "react";import type { ReactNode } from "react"; let attempts = 0;const cache = new Map<string, Promise<string>>();function loadProfile(id: string): Promise<string> { if (!cache.has(id)) { const attempt = ++attempts; cache.set(id, new Promise((resolve, reject) => setTimeout(() => { if (attempt === 1) reject(new Error("503 from /api/profile")); else resolve(`Ada Lovelace (loaded on attempt ${attempt})`); }, 600) )); } return cache.get(id)!;} class ErrorBoundary extends Component<{ onRetry: () => void; children: ReactNode }, { error: Error | null }> { state = { error: null as Error | null }; static getDerivedStateFromError(error: Error) { return { error }; } render() { if (!this.state.error) return this.props.children; return ( <div role="alert"> <p>Could not load the profile ({this.state.error.message}).</p> <button onClick={() => { this.props.onRetry(); this.setState({ error: null }); }}>Retry</button> </div> ); }} function Profile({ id }: { id: string }) { const name = use(loadProfile(id)); return <p>Signed in as {name}</p>;} export default function App() { const [shouldEvict, setShouldEvict] = useState(true); return ( <div> <label> <input type="checkbox" checked={shouldEvict} onChange={(e) => setShouldEvict(e.target.checked)} /> Evict the cached promise on retry </label> <ErrorBoundary onRetry={() => { if (shouldEvict) cache.delete("ada"); }}> <Suspense fallback={<p>Loading profile...</p>}> <Profile id="ada" /> </Suspense> </ErrorBoundary> </div> );}

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.
  • resetKeys for "the inputs changed, the old error no longer applies", like a new customer id.
  • A key on 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.
Predict the outputJavaScript

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>
Need a nudge? Hints walk you through it.

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?

Boundaries in a dashboard app
RootBoundarylast resort: "Something went wrong" + reloadRevenueChartChartBoundaryrevenue chartMapEmbedEmbedBoundarythird-party mapOrdersTablecore content, no own boundaryReportsPageRouteBoundaryper page, key=pathnameAppShellnav, header, account menuroot

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.

1/4

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.tsx files 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.

Put it in order6 steps

A child of a boundary throws during render. Put React's steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

main.tsx
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.message in 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 the pairs0/5 matched

Match each tool to the job it does.

Choose an item, then its match on the other side.
Key terms
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 PriceWidget inside ReportsPage. More useful than the JS stack for UI bugs.
resetKeys
A react-error-boundary prop: when any value in the array changes, the boundary clears its error and remounts its children.
onCaughtError / onUncaughtError
React 19 createRoot options 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.