Error boundaries
Overview
Bugs happen: an API returns an unexpected shape, a value is undefined where you didn’t expect it, a third-party component throws. In React, an error thrown while rendering that nothing catches unmounts the entire app — the user is left with a blank white page. Error boundaries contain the damage: they catch errors in the part of the tree they wrap and show fallback UI instead.
Why React unmounts everything
It might seem harsh, but showing broken UI is worse than showing none. A half-rendered checkout page that displays the wrong total could cost a user money. So React’s default is: if rendering fails and nobody handles it, remove the UI. Error boundaries let you decide what to show instead.
Using react-error-boundary
React’s built-in error boundary API only exists for class components. Rather than writing a class, almost every project uses the small react-error-boundary package:
npm install react-error-boundaryimport { ErrorBoundary } from 'react-error-boundary';
function ChartError({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Couldn’t load the chart.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
<ErrorBoundary FallbackComponent={ChartError}>
<SalesChart />
</ErrorBoundary>If SalesChart (or anything inside it) throws while rendering, the boundary renders ChartError instead. Everything outside the boundary keeps working.
Three ways to give the fallback:
fallback={<p>Something went wrong</p>}— static JSX,FallbackComponent={ChartError}— a component receivingerrorandresetErrorBoundary,fallbackRender={({ error, resetErrorBoundary }) => …}— an inline function.
Retrying
resetErrorBoundary() clears the error and renders the children again — useful when the failure was temporary. Use onReset to reset any state that caused the error, and resetKeys to reset automatically when something changes:
<ErrorBoundary FallbackComponent={CourseError} resetKeys={[courseId]}>
<CourseDetails courseId={courseId} />
</ErrorBoundary>Navigate to another course and the boundary resets itself, giving the new course a fresh try.
What boundaries catch — and don’t
Error boundaries catch errors thrown during rendering of the components below them — including in hooks and lifecycle code and in rejected promises read with use. They do not catch errors in:
- event handlers (they don’t run during rendering),
- async code like
setTimeoutcallbacks or unawaited promises, - server-side rendering,
- the error boundary itself (it’s handled by the next boundary up).
Routing async errors to a boundary
For event handlers, the usual approach is to handle errors locally — show a message near the button. When you’d rather show the boundary’s fallback, there are two ways:
// 1. Actions in a transition: errors thrown inside reach the nearest boundary
const [isPending, startTransition] = useTransition();
function handleRefresh() {
startTransition(async () => {
await refreshLessons(); // if this throws, the boundary shows its fallback
});
}// 2. useErrorBoundary from react-error-boundary
import { useErrorBoundary } from 'react-error-boundary';
function ExportButton() {
const { showBoundary } = useErrorBoundary();
async function handleExport() {
try {
await exportReport();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleExport}>Export</button>;
}Where to put boundaries
Think about how much of the screen should disappear when something fails:
- One at the top of the app, with a friendly “Something went wrong — reload” page. This is your last line of defence; never ship without it.
- One per route (routers provide this — React Router’s route
ErrorBoundary, Next.jserror.jsfiles), so the navigation stays usable. - Around independent widgets — charts, comments, recommendations — so one failing feature doesn’t take the page down.
Don’t wrap every component: too many boundaries scatter error messages across the page, and users can’t tell what’s broken.
Reporting errors
Users rarely report errors; you need to know about them anyway. Send them to a monitoring service like Sentry, Datadog or your own logging endpoint:
<ErrorBoundary
FallbackComponent={AppError}
onError={(error, info) => {
reportError(error, { componentStack: info.componentStack });
}}
>
<App />
</ErrorBoundary>React 19 also lets you hook into errors for the whole app at the root:
createRoot(document.getElementById('root'), {
onCaughtError: (error, info) => reportError(error, info), // caught by a boundary
onUncaughtError: (error, info) => reportError(error, info), // not caught — app unmounted
onRecoverableError: (error) => console.warn(error), // React recovered automatically
}).render(<App />);The class component API
For reference, here’s what react-error-boundary does under the hood — you’ll see this in older codebases:
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error }; // render the fallback next
}
componentDidCatch(error, info) {
reportError(error, info.componentStack);
}
render() {
if (this.state.error) return this.props.fallback;
return this.props.children;
}
}Writing good fallback UI
- Say what went wrong in plain language, and what the user can do: “Couldn’t load your progress. Try again, or check your connection.”
- Offer a retry where it might help.
- Keep the rest of the page usable — navigation, other widgets.
- In development, show
error.messageto help debugging; in production, don’t expose stack traces to users.
Errors are part of the design. Decide what users see when each part of the page fails, the same way you design loading and empty states.
A resilient dashboard
Using react-error-boundary, wrap each dashboard widget (ProgressChart, RecentLessons) in its own ErrorBoundary with a WidgetError fallback that shows “This widget couldn’t load.” and a “Try again” button calling resetErrorBoundary. Log errors with onError to a reportError(error, info) function. Then make a “Refresh” button inside RecentLessons whose async click handler failure is shown by the boundary (use useTransition, or useErrorBoundary().showBoundary).
import { ErrorBoundary } from 'react-error-boundary';
// provided: ProgressChart, RecentLessons, reportError, refreshLessons
function WidgetError(/* props */) {
// your code here
}
export function Dashboard() {
// your code here
}import { useTransition } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
function WidgetError({ resetErrorBoundary }) {
return (
<div role="alert" className="widget-error">
<p>This widget couldn’t load.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function Widget({ children }) {
return (
<ErrorBoundary FallbackComponent={WidgetError} onError={(error, info) => reportError(error, info)}>
{children}
</ErrorBoundary>
);
}
function RecentLessons() {
const [isPending, startTransition] = useTransition();
function handleRefresh() {
// Errors thrown inside a transition reach the nearest error boundary
startTransition(async () => {
await refreshLessons();
});
}
return (
<section>
<h2>Recent lessons</h2>
<button onClick={handleRefresh} disabled={isPending}>
{isPending ? 'Refreshing…' : 'Refresh'}
</button>
</section>
);
}
export function Dashboard() {
return (
<main className="dashboard">
<Widget><ProgressChart /></Widget>
<Widget><RecentLessons /></Widget>
</main>
);
}Summary
- Without an error boundary, an error thrown while rendering unmounts the whole React app.
- An error boundary catches render errors in its subtree and shows a fallback; only that area is replaced.
- React’s built-in boundaries are class components; most apps use the
react-error-boundarypackage. - Boundaries don’t catch event-handler or async errors directly — use transitions or
showBoundaryto route them there. - Place boundaries around independent features, offer a retry, and report errors to a monitoring service.