React Error Boundaries: Graceful Failure Patterns Guide
Learn how React error boundaries catch render-time failures and pair with Suspense reset keys to recover gracefully — without crashing the whole app.

React's default error behavior is brutal: one unhandled render exception and the entire component tree unmounts, leaving users a blank white screen with no path back. React error boundaries exist to contain that blast radius, but a surprising number of teams reach for them only after a production incident, and even then they often wire them up incompletely.
Three gaps come up repeatedly: boundaries that catch render errors but silently miss async failures, Suspense fallbacks that don't reset on navigation, and no real recovery mechanism beyond "reload the page." The react-error-boundary library closes most of these with less boilerplate than a raw class component approach. This guide covers the full pattern: placement strategy, async error wiring, and reset keys, so your app fails predictably and recovers gracefully.
Boundaries are not a one-size-fits-all safety net. Wrapping the entire app in a single boundary is better than nothing, but it still shows users a blank error screen. The real goal is scoped containment: a broken sidebar should never take down a working main panel.
What you'll learn
- Why error boundaries exist and what they actually catch
- Scoping boundaries to limit blast radius
- Using react-error-boundary instead of raw class components
- Pairing error boundaries with Suspense
- Reset keys and automatic recovery
- Async errors that boundaries silently miss
- Reporting errors to monitoring services
- Frequently Asked Questions
Why error boundaries exist and what they actually catch
An error boundary is a React component that catches JavaScript errors thrown during rendering, in lifecycle methods, and in constructors of the component tree below it. When the caught tree throws, the boundary renders a fallback UI instead of propagating the crash.
Before error boundaries, a single render exception from a deeply nested widget would silently unmount the whole tree. React 16 formalized boundaries because leaving users on a blank screen with no feedback is worse than showing a recoverable error state.
What they catch:
- Errors thrown during
renderin class or function components - Errors thrown inside
useLayoutEffect(synchronous) - Errors in constructor calls
What they don't catch (this is where teams get burned):
- Errors thrown inside event handlers (
onClick,onChange, etc.) - Errors thrown in
useEffect(async lifecycle) - Errors in async code (
setTimeout,fetch,async/await) - Server-side rendering errors
That's a long list of misses. A boundary that only covers render is half the story.
Scoping boundaries to limit blast radius
The placement of boundaries matters more than most teams realize. A single root-level boundary is a last resort, not a strategy.
Consider a typical product dashboard. It has navigation, a data table, a chart widget, and a notification sidebar. If the chart widget receives malformed data and throws, only the chart panel should fail. The rest of the UI should stay fully interactive. That requires a boundary around the chart, not just at the app root.
A practical hierarchy looks like this:
<AppErrorBoundary fallback={<AppCrashScreen />}> {/* last resort */}
<Layout>
<Sidebar />
<Main>
<SectionErrorBoundary fallback={<SectionError />}> {/* per feature */}
<ChartWidget />
</SectionErrorBoundary>
<DataTable />
</Main>
</Layout>
</AppErrorBoundary>
Three zones work well for most apps: a root-level catch-all, section-level boundaries around each major feature, and widget-level boundaries for third-party embeds or data-dependent micro-components.
The trade-off here is honest: too many boundaries add maintenance weight. Every new boundary is a new fallback UI to design and a new reset behavior to test. Start at the section level, add widget-level boundaries only where a widget is genuinely isolated and prone to data errors.
Using react-error-boundary instead of raw class components
React requires error boundaries to be class components because componentDidCatch and getDerivedStateFromError are class-only lifecycle methods. Writing a raw class component for every boundary gets tedious fast, and it can't use hooks.
The react-error-boundary library wraps this complexity into a composable <ErrorBoundary> component that accepts props:
import { ErrorBoundary } from 'react-error-boundary';
function ChartFallback({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
<p>Chart failed to load.</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function ChartSection() {
return (
<ErrorBoundary FallbackComponent={ChartFallback}>
<ChartWidget />
</ErrorBoundary>
);
}
The FallbackComponent receives the caught error and a resetErrorBoundary callback. Calling resetErrorBoundary clears the error state and re-renders the original tree, which is exactly the "try again" button users expect.
The onError prop lets you pipe the error and component stack to your monitoring tool before showing the fallback:
<ErrorBoundary
FallbackComponent={ChartFallback}
onError={(error, info) => {
logToSentry(error, { componentStack: info.componentStack });
}}
>
<ChartWidget />
</ErrorBoundary>
Pairing error boundaries with Suspense
Suspense and error boundaries are two sides of the same coin. Suspense handles the loading state when a promise is pending; an error boundary handles the failure state when a promise rejects. React's data-fetching model assumes both are present.
<ErrorBoundary FallbackComponent={DataFallback}>
<Suspense fallback={<Skeleton />}>
<UserProfile userId={userId} />
</Suspense>
</ErrorBoundary>
The boundary must wrap the Suspense, not sit inside it. When a suspended component's promise rejects, React throws the error upward through the tree: the first error boundary it hits handles it. If the boundary is inside the Suspense, the Suspense catches the throw first and treats it as a pending state forever.
A comparison of the two patterns:
| Pattern | What happens on rejection |
|---|---|
<ErrorBoundary> wraps <Suspense> | Rejection propagates up to boundary; fallback renders |
<Suspense> wraps <ErrorBoundary> | Rejection may not surface; loading spinner hangs |
No boundary around <Suspense> | Rejection crashes entire tree above the Suspense |
Always wrap Suspense in an error boundary. Without one, a rejected promise gives you the same blank screen problem boundaries were invented to solve.
Reset keys and automatic recovery
The resetErrorBoundary callback handles manual retries. But many errors are transient: a brief network outage, a race condition on mount. Users shouldn't have to click "try again" after every route change.
react-error-boundary supports resetKeys: an array of values that, when changed, automatically reset the boundary. This pairs well with route params or data IDs:
function UserPage({ userId }: { userId: string }) {
return (
<ErrorBoundary
FallbackComponent={UserFallback}
resetKeys={[userId]}
>
<Suspense fallback={<Skeleton />}>
<UserProfile userId={userId} />
</Suspense>
</ErrorBoundary>
);
}
When the user navigates from one profile to another, userId changes, the boundary resets, and the new profile fetches fresh. Without this, navigating away from a broken profile and back leaves the error fallback pinned even though the new data might be fine.
The onReset prop fires when the boundary resets, letting you clear any related state:
<ErrorBoundary
FallbackComponent={UserFallback}
resetKeys={[userId]}
onReset={() => queryClient.invalidateQueries(['user', userId])}
>
Async errors that boundaries silently miss
The most common misconception: wrapping a component in an error boundary doesn't catch errors thrown inside that component's event handlers or effects.
// This error is NOT caught by any error boundary above it
function DeleteButton() {
const handleClick = async () => {
const result = await deleteRecord(id); // throws on 500
// boundary never sees this
};
return <button onClick={handleClick}>Delete</button>;
}
The fix for event handler errors is to use local state:
function DeleteButton() {
const [error, setError] = useState<Error | null>(null);
const handleClick = async () => {
try {
await deleteRecord(id);
} catch (err) {
setError(err as Error);
}
};
if (error) return <span>Delete failed: {error.message}</span>;
return <button onClick={handleClick}>Delete</button>;
}
For useEffect errors, the standard approach is to store the error in state and then re-throw it during render so the boundary can catch it:
function DataWidget() {
const [renderError, setRenderError] = useState<Error | null>(null);
useEffect(() => {
fetchData().catch((err) => setRenderError(err));
}, []);
if (renderError) throw renderError; // now the boundary catches it
return <div>...</div>;
}
This pattern is the bridge between async failure and boundary-catchable failure. It's not pretty, but it works reliably and keeps error reporting consistent.
Reporting errors to monitoring services
An error boundary that swallows errors silently is worse than no boundary. You lose production signal. The onError prop is where you connect to Sentry, Datadog, or any custom logging:
import * as Sentry from '@sentry/react';
<ErrorBoundary
FallbackComponent={SectionFallback}
onError={(error, info) => {
Sentry.captureException(error, {
extra: { componentStack: info.componentStack },
});
}}
>
The componentStack field in info is the React component tree at the point of failure. It's more useful for triaging UI bugs than a raw JavaScript stack trace because it names components, not minified function names.
At Laxaar, we treat the onError callback as non-optional. Every boundary that ships to production must have monitoring wired in. Silent error states make dashboards look healthy while users are hitting broken UI, and that gap gets harder to close the longer it goes undetected.
For teams using Sentry, the Sentry.ErrorBoundary wrapper is a drop-in replacement for react-error-boundary's ErrorBoundary and includes automatic reporting. The trade-off: it couples your error boundary to Sentry directly, making it harder to swap providers later. We usually prefer the explicit onError approach for that reason.
Frequently Asked Questions
Can a function component be an error boundary?
No. As of React 19, error boundaries must still be class components under the hood because getDerivedStateFromError and componentDidCatch are class lifecycle methods with no hooks equivalent. Libraries like react-error-boundary wrap a class boundary internally so you can use it as a declarative prop-driven component without writing a class yourself.
What happens if the fallback component itself throws?
The boundary that rendered the fallback can't catch that error. The next error boundary up the tree handles it. This is a real risk if your fallback does data fetching or renders complex UI. Keep fallbacks simple (static markup, an icon, and a retry button). No data loading, no business logic.
Do error boundaries work with React Server Components?
Partially. Error boundaries only run client-side. For server-rendered components in the Next.js App Router, the error.tsx convention serves a similar role: it defines a per-route error UI that Next.js renders when a server component throws. At Laxaar, we treat error.tsx files and client error boundaries as complementary layers, not alternatives.
Should we reset the boundary after a successful retry?
Yes. If the user clicks "try again" and the component loads successfully, the boundary's error state clears automatically because resetErrorBoundary causes a re-render from a clean slate. You don't need to manually signal success to the boundary, but do call onReset if any parent state (like a query cache) needs refreshing alongside the reset.
How do we test error boundary behavior?
Suppress React's intentional console.error output in test setup, then render the component that throws inside your boundary and assert the fallback appears. Libraries like @testing-library/react work fine. One reliable pattern at Laxaar is to create a <ThrowError shouldThrow /> helper component for test suites rather than mocking internal component failures directly.
Error boundaries are one of those patterns that feel optional until the first time a third-party widget or bad API payload takes down a production UI. Getting the placement right, wiring async errors through state re-throws, and attaching monitoring from day one keeps your React app resilient without heroic incident response.
If you want a team that ships production-ready React applications with error handling, observability, and recovery patterns baked in from the start, see how we approach custom software development or get in touch with the Laxaar team to talk through your project.
Working on something like this?
Get a fixed scope, timeline, and price within one business day — no obligation.


