Error Boundaries and Graceful Degradation in React and Next.js
A third-party chart widget throws on one malformed data point, and the whole dashboard goes white. Navigation, filters, the export button: all gone, because without a boundary, React's answer to a render error is clearing the UI rather than showing anything partial. Error boundaries exist so one broken widget costs you one widget. This post covers how they work in plain React, how Next.js maps them onto routes, how to give users a retry that won't loop forever, and how to make sure the error actually reaches you.
Versions as of November 2026: React 19.3.1, Next.js 16.4.5, @sentry/nextjs and @sentry/react 11.11.0, react-error-boundary 6.1.6.
What a boundary catches, and what it doesn't
An error boundary is a component that catches errors thrown while rendering its children and shows a fallback instead. Per the React docs, there's still no hook equivalent; you write it as a class with static getDerivedStateFromError (to switch to the fallback) and componentDidCatch (to log). The docs suggest writing one such class and reusing it everywhere, or using the react-error-boundary package.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
// info.componentStack names the component that threw and its parents
reportError(error, { componentStack: info.componentStack });
}
render() {
if (this.state.error) return this.props.fallback;
return this.props.children;
}
}
The list of what boundaries don't catch is short and important. From the same page:
- errors in event handlers;
- errors during server-side rendering;
- errors thrown in the boundary itself, rather than its children;
- asynchronous code such as
setTimeoutorrequestAnimationFramecallbacks.
There's one useful exception: errors thrown inside the function you pass to startTransition from useTransition are caught by the nearest boundary. That gives you a clean way to route an async failure into the boundary instead of a hand-rolled error state:
function SaveButton({ draft }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() =>
startTransition(async () => {
await saveDraft(draft); // if this throws, the nearest boundary shows its fallback
})
}
>
Save
</button>
);
}
For a click handler where you'd rather show an inline message than swap the whole section out, the Next.js guide recommends the boring approach: try/catch and put the error in state.
Place boundaries by blast radius
Where you put boundaries matters more than how fancy the fallback is. My rule: one boundary per thing a user could reasonably keep using without the broken part.
- App level: a last resort so you never show a blank page. Plain HTML, a reload link, a support contact.
- Route or page level: the page failed, but the header and navigation still work, so people can go somewhere else.
- Widget level: a chart, a comments list, a recommendations rail. The fallback is a small "couldn't load this" card sized like the real thing, so the layout doesn't jump.
Don't wrap every component. A boundary around a single button just hides bugs, and nested fallbacks inside fallbacks look worse than one clear message.
How Next.js maps boundaries onto routes
In the App Router, an error.tsx file in a route segment becomes a React error boundary around that segment. It must be a Client Component. Errors bubble to the nearest parent boundary, so you can nest them at different levels of the route tree.
The detail that catches people: error.tsx wraps loading, not-found, page and nested layouts, but not the layout.tsx in the same segment. An error in app/dashboard/layout.tsx is handled by app/error.tsx. For the root layout you need app/global-error.tsx, which replaces the root layout when active and therefore has to render its own <html> and <body>. The docs add that it doesn't get your global styles, and since it's a Client Component it can't export metadata; use React's <title> instead.
Recent Next.js releases changed the props. As of 16.3.0, retry is the stable recovery prop (it was unstable_retry in 16.2.0). retry() re-fetches and re-renders the segment; the older reset() only clears the error state without re-fetching, so it can't recover from a Server Component error. The error prop is typed unknown now, because a Client Component can throw anything, so narrow it before reading fields:
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';
export default function DashboardError({ error, retry }: { error: unknown; retry: () => void }) {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
const digest = error instanceof Error && 'digest' in error ? String(error.digest) : null;
return (
<div role="alert">
<h2>The dashboard didn't load</h2>
<p>Your other pages still work. You can try again or come back in a minute.</p>
<button onClick={() => retry()}>Try again</button>
{digest && <p>Reference: {digest}</p>}
</div>
);
}
That digest matters. In production, errors from Server Components reach the client with a generic message and a digest hash, so you don't leak server details. Showing the digest gives support something to match against server logs.
For boundaries that aren't tied to a route segment, Next.js 16.3.0 also made catchError stable. It builds a boundary component from a fallback function, and unlike a hand-written class it knows not to swallow the special errors that redirect() and notFound() throw internally. Its error state also clears when you navigate to another route.
Retry without a retry loop
A "Try again" button that immediately fails again, forever, is worse than no button. A few habits:
- Cap automatic retries. If you retry on mount, do it once or twice with a delay, then stop and show the manual button.
- Reset on a real change.
react-error-boundary'sresetKeysprop resets a triggered boundary when one of the keys changes, so navigating to a different record clears the error for free. - Clear the cause in
onReset. If bad cached data caused the crash, drop it before re-rendering, or the retry renders the same bad data. - Know your data layer's retries. TanStack Query, for example, already retries failed queries 3 times with exponential backoff by default; stacking your own retries on top multiplies requests.
import { ErrorBoundary } from 'react-error-boundary';
<ErrorBoundary
resetKeys={[invoiceId]}
onReset={() => queryClient.removeQueries({ queryKey: ['invoice', invoiceId] })}
onError={(error, info) => Sentry.captureException(error, { extra: { componentStack: info.componentStack } })}
fallbackRender={({ resetErrorBoundary }) => (
<div role="alert">
<p>We couldn't show this invoice.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)}
>
<InvoiceDetails id={invoiceId} />
</ErrorBoundary>
Reporting errors so you actually hear about them
A fallback hides the error from users. Without reporting, it hides it from you too.
Plain React 19. createRoot takes three hooks: onCaughtError (a boundary caught it), onUncaughtError (nothing did) and onRecoverableError (React recovered by itself). Each gets the error and an errorInfo with the componentStack. Sentry's React docs plug straight into them:
import { createRoot } from 'react-dom/client';
import * as Sentry from '@sentry/react';
const root = createRoot(document.getElementById('root'), {
onUncaughtError: Sentry.reactErrorHandler(),
onCaughtError: Sentry.reactErrorHandler(),
onRecoverableError: Sentry.reactErrorHandler(),
});
root.render(<App />);
Next.js. Sentry's manual setup captures server errors through the onRequestError hook in instrumentation.ts, and calls Sentry.captureException(error) in a useEffect inside global-error.tsx:
// instrumentation.ts (excerpt; register() setup is in Sentry's guide)
import * as Sentry from '@sentry/nextjs';
export const onRequestError = Sentry.captureRequestError;
Production component stacks are minified. The React docs point out you can decode them with source maps, the same way as regular stack traces, so upload source maps as part of your build or the reports will be hard to read.
If Sentry isn't settled yet, our Sentry vs Datadog comparison puts the two side by side. And if you triage with an AI assistant, see our Sentry MCP server page, or the Datadog MCP server one if that's your stack.
Graceful degradation beyond boundaries
Boundaries handle crashes. Plenty of failures aren't crashes, and you should design for them on purpose:
- Expected errors are data. Validation failures and "not found" are normal outcomes. Next.js recommends returning them from Server Actions and rendering them, and calling
notFound()for missing records, rather than throwing. Our Server Actions guide goes deeper. - Show stale data rather than nothing. If a refresh fails but you have cached data, show it with a "last updated" note.
- Make optional sections optional. Recommendations or an activity feed failing shouldn't block checkout.
- Test the failure paths. Throw on purpose in a test and assert the fallback renders; React DevTools can also toggle a boundary into its error state. Our post on testing React components with Vitest covers the setup.
A quick audit for your app
- Is there a root-level fallback, and in Next.js a
global-error.tsxwith its own<html>and<body>? - Does each major route segment have an
error.tsx, remembering it doesn't cover its own layout? - Do independent widgets have their own small boundary with a same-sized fallback?
- Are async and event-handler errors handled with
try/catchor routed throughstartTransition? - Are errors reported from boundaries, root hooks and the server, with source maps uploaded?
- Can a user retry, and is there a cap so retries can't loop?
Written by AIDToolStack Editorial
Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.
Sources
- react.dev/reference/react/Component
- registry.npmjs.org/react/latest
- registry.npmjs.org/next/latest
- registry.npmjs.org/@sentry/nextjs/latest
- registry.npmjs.org/react-error-boundary/latest
- nextjs.org/docs/app/getting-started/error-handling
- nextjs.org/docs/app/api-reference/file-conventions/error
- nextjs.org/docs/app/api-reference/functions/catchError
- tanstack.com/query/latest/docs/framework/react/guides/important-defaults
- react.dev/reference/react-dom/client/createRoot
- docs.sentry.io/platforms/javascript/guides/react/features/error-boundary/
- docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
- github.com/bvaughn/react-error-boundary
- registry.npmjs.org/@sentry/react/latest
Related Posts
Explore on AIDToolStack
Discover tools and servers featured in our directory.
AI Tools
MCP Servers
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.