React Error Boundaries: Handling Errors Gracefully
The API starts returning user.address as null instead of an object, and somewhere deep in a profile card you call user.address.city. You get TypeError: Cannot read properties of null (reading 'city'), React unmounts the whole tree, and your users are staring at a blank white page. One small card took down the entire app.
Error Boundaries are how you stop that. They catch errors thrown while rendering a subtree, let you log them, and show a fallback in place of the broken part. This post covers how to write one, what they don't catch, the react-error-boundary package, testing, production reporting, and how they fit with React Router.
Since React 16, an uncaught error during rendering unmounts the entire root. The React team chose this on purpose: showing a half-broken UI with corrupted state was judged worse than showing nothing. Boundaries let you decide which smaller piece gets removed instead.
What Are Error Boundaries?
You build one as a class component with one or both of these lifecycle methods:
- static getDerivedStateFromError(error): Called during rendering when a descendant throws. You update state here to trigger a fallback UI on the next render.
- componentDidCatch(error, errorInfo): Called after the error has been caught and the tree has re-rendered with the fallback. Use this to log the error to an external service.
Think of it as a catch block for a subtree. If a child throws during rendering, in a lifecycle method, or in its constructor, the error goes up to the nearest boundary above it.
Error Boundaries catch errors from descendant components and render a fallback instead
Creating Your First Error Boundary
This is one of the few places where you still need a class component. There's no hook version of these two lifecycle methods. You write it once and reuse it everywhere, so it's not a big deal in practice.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
// Called during render when a descendant throws.
// Return new state to trigger fallback UI.
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
// Called after render when a descendant threw.
// Use for side-effects: logging, reporting.
componentDidCatch(error, errorInfo) {
console.error('ErrorBoundary caught:', error, errorInfo);
// logErrorToService(error, errorInfo.componentStack);
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong.</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false, error: null })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
Using Your Error Boundary
Wrap the parts of the tree that might throw. Note that this basic version ignores the fallback prop used on the second boundary below; the flexible version later in the post handles it.
import ErrorBoundary from './ErrorBoundary';
import UserProfile from './UserProfile';
import Dashboard from './Dashboard';
function App() {
return (
<div>
<Navigation />
{/* Wrap only the part that might fail */}
<ErrorBoundary>
<UserProfile userId={userId} />
</ErrorBoundary>
{/* Different boundary for a different section */}
<ErrorBoundary fallback={<p>Dashboard unavailable</p>}>
<Dashboard />
</ErrorBoundary>
<Footer />
</div>
);
}
A single boundary at the root is basically a global try/catch: you swap a blank page for an error page. Put boundaries around individual features too, so one broken section doesn't hide everything else.
What Error Boundaries Do NOT Catch
This is where most confusion comes from. Boundaries only catch errors thrown while React is rendering or running lifecycle methods. A lot of real-world errors happen outside that.
| Error Source | Caught by Error Boundary? | How to Handle Instead |
|---|---|---|
| Errors during rendering | Yes | Error Boundary handles it |
| Errors in lifecycle methods | Yes | Error Boundary handles it |
| Errors in constructors of children | Yes | Error Boundary handles it |
| Errors in event handlers | No | Use try/catch inside the handler |
| Async errors (setTimeout, fetch) | No | Use try/catch with async/await |
| Server-side rendering errors | No | Handle in SSR framework (Next.js) |
| Errors inside the boundary itself | No | Use a parent Error Boundary |
// Error Boundaries do NOT catch this:
function DeleteButton({ id }) {
const handleClick = () => {
// This error won't reach the Error Boundary
throw new Error('Oops');
};
return <button onClick={handleClick}>Delete</button>;
}
// You must use try/catch in event handlers:
function DeleteButton({ id }) {
const [error, setError] = React.useState(null);
const handleClick = async () => {
try {
await deleteItem(id);
} catch (err) {
setError(err.message);
}
};
if (error) return <p className="error">{error}</p>;
return <button onClick={handleClick}>Delete</button>;
}
Advanced Patterns
Accepting a Custom Fallback via Props
A hardcoded "Something went wrong" gets old fast. Accept a fallback prop so each place that uses the boundary decides what to show:
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
reset = () => this.setState({ hasError: false, error: null });
render() {
if (this.state.hasError) {
// Accept a render prop, a fallback element, or use a default
if (typeof this.props.fallback === 'function') {
return this.props.fallback({
error: this.state.error,
reset: this.reset,
});
}
return this.props.fallback ?? <DefaultErrorFallback />;
}
return this.props.children;
}
}
// Usage with render prop:
<ErrorBoundary
fallback={({ error, reset }) => (
<div>
<p>Widget failed: {error.message}</p>
<button onClick={reset}>Retry</button>
</div>
)}
onError={(err, info) => Sentry.captureException(err, { extra: info })}
>
<ComplexWidget />
</ErrorBoundary>
The react-error-boundary Library
In most projects I'd skip writing the class myself and use react-error-boundary. It covers fallbacks, reset logic and resetKeys, and gives you a useErrorBoundary hook so function components can push an error to the nearest boundary by hand.
Install the package
Run npm install react-error-boundary in your project.
Use ErrorBoundary component
Import the ErrorBoundary it ships and pass your fallback through the FallbackComponent prop.
Use useErrorBoundary hook (optional)
Call showBoundary(error) inside async code to manually trigger the boundary.
import { ErrorBoundary, useErrorBoundary } from 'react-error-boundary';
// A proper fallback component
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert" className="error-container">
<h2>Something went wrong</h2>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
// Using useErrorBoundary in an async context
function DataFetcher({ url }) {
const { showBoundary } = useErrorBoundary();
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch(url)
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(setData)
.catch(showBoundary); // Delegates to nearest ErrorBoundary
}, [url, showBoundary]);
return data ? <Display data={data} /> : <Spinner />;
}
// Wiring it all together
function App() {
return (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => window.location.reload()}
onError={(error, info) => console.error(error, info)}
>
<DataFetcher url="/api/users" />
</ErrorBoundary>
);
}
Nesting Error Boundaries Strategically
Boundaries nest, and that's where they get useful. A crashing chart widget on a dashboard shouldn't take the navigation bar or sidebar with it. An error goes to the closest boundary only, so each one protects its own section.
Nested Error Boundaries isolate failures. The ChartWidget crash doesn't affect ActivityFeed or DataTable
Testing Error Boundaries
To test a boundary you need a child that throws on purpose. With Jest and React Testing Library that's a few lines.
import { render, screen, fireEvent } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';
// A component that throws when "shouldThrow" is true
function Bomb({ shouldThrow }) {
if (shouldThrow) {
throw new Error('Boom!');
}
return <p>All good</p>;
}
test('renders fallback when child throws', () => {
render(
<ErrorBoundary>
<Bomb shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText(/something went wrong/i)).toBeInTheDocument();
});
test('renders children when no error', () => {
render(
<ErrorBoundary>
<Bomb shouldThrow={false} />
</ErrorBoundary>
);
expect(screen.getByText('All good')).toBeInTheDocument();
});
// Reusable "Boom" component for testing
function ThrowError({ message = 'Test error' }) {
throw new Error(message);
}
// Test reset functionality
test('reset clears the error state', () => {
const { rerender } = render(
<ErrorBoundary>
<ThrowError />
</ErrorBoundary>
);
expect(screen.getByRole('button', { name: /try again/i })).toBeInTheDocument();
// Simulate the user clicking "Try again"
fireEvent.click(screen.getByRole('button', { name: /try again/i }));
// Re-render with a non-throwing child
rerender(
<ErrorBoundary>
<p>Recovered!</p>
</ErrorBoundary>
);
expect(screen.getByText('Recovered!')).toBeInTheDocument();
});
// React logs caught errors to console.error by default.
// Suppress noise in tests with a beforeEach/afterEach spy.
let consoleSpy;
beforeEach(() => {
consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
});
// Now your test output won't be polluted with expected error logs
test('shows fallback without console noise', () => {
render(
<ErrorBoundary>
<ThrowError message="silent error" />
</ErrorBoundary>
);
expect(screen.getByText(/something went wrong/i)).toBeInTheDocument();
// Optionally verify componentDidCatch was still called:
expect(consoleSpy).toHaveBeenCalled();
});
Error Reporting in Production
A fallback UI hides the problem from users, but you still need to know about it. componentDidCatch is where you send the error to a monitoring service like Sentry, Datadog or LogRocket, along with the component stack.
In development, Create React App, Vite and Next.js show a full-screen error overlay even when a boundary caught the error, and React still prints "The above error occurred in the <X> component" to the console. Close the overlay and your fallback is usually sitting underneath. Check in a production build before you start debugging the boundary. Also, minified production stack traces are close to useless in Sentry unless you upload source maps as part of your build.
import * as Sentry from '@sentry/react';
class ErrorBoundary extends React.Component {
state = { hasError: false, eventId: null };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, { componentStack }) {
const eventId = Sentry.captureException(error, {
contexts: {
react: { componentStack },
},
});
this.setState({ eventId });
}
render() {
if (this.state.hasError) {
return (
<div>
<h2>An error occurred.</h2>
<button
onClick={() =>
Sentry.showReportDialog({ eventId: this.state.eventId })
}
>
Report this issue
</button>
</div>
);
}
return this.props.children;
}
}
// Sentry also ships its own ErrorBoundary with the same API:
// import { ErrorBoundary } from '@sentry/react';
// It does all of the above automatically.
Error Boundary Checklist for Production Apps
- Top-level boundary: Always have one root Error Boundary as a last resort fallback.
- Feature-level boundaries: Wrap independent features (widgets, panels, routes) with their own boundaries.
- Route-level boundaries: Use boundaries per route so a broken page doesn't crash navigation.
- Error reporting: Always log to an external service in
componentDidCatch. - User-friendly fallback: Show a message, not a blank screen. Offer a "Try again" button where sensible.
- Reset on navigation: Use the
resetKeysprop (react-error-boundary) to auto-reset when the user navigates away. - Test your boundaries: Write at least one test that verifies the fallback renders on error.
- Don't swallow errors silently: Even if you show a fallback, always report the original error.
Error Boundaries with React Router
With React Router v6 data routers, you can set an errorElement on a route. It works as a route-level boundary and also catches errors from loaders and actions. If you want a smaller piece of a page to fail without replacing the whole route, you still need your own boundary inside it.
import { createBrowserRouter, RouterProvider, useRouteError } from 'react-router-dom';
// A route-error component (receives the thrown value via useRouteError)
function RouteErrorPage() {
const error = useRouteError();
return (
<div>
<h1>Page Error</h1>
<p>{error.statusText || error.message}</p>
</div>
);
}
const router = createBrowserRouter([
{
path: '/',
element: <Root />,
errorElement: <RouteErrorPage />, // Catches loader/action errors
children: [
{
path: 'dashboard',
element: (
// Still use your own ErrorBoundary for component-level errors
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
),
loader: dashboardLoader,
errorElement: <RouteErrorPage />, // Catches loader errors
},
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}
Mistakes I see most often
Where boundaries go wrong
- Expecting them to catch everything: a failed
fetchin a click handler or a rejected promise inuseEffectnever reaches a boundary on its own. Either handle it locally or pass it on withshowBoundary. - A "Try again" button that can't work: resetting the boundary re-renders the same children with the same props. If the bad data is still there, it throws again right away. Reset with
resetKeystied to the thing that changed (route, user id, query), or refetch inonReset. - Wrapping every component: boundaries around tiny pieces give you a page full of little error boxes. Wrap things a user would think of as one unit: a widget, a panel, a route.
- Swallowing the error: a nice fallback with no reporting means you find out from a support ticket. Always send it somewhere in
componentDidCatchoronError. - Showing
error.messageto users: fine for internal tools, but in a public app it can leak details and usually means nothing to the user anyway.
When wouldn't I bother? For a small internal tool or a prototype, one root boundary plus error reporting is usually enough, and adding a boundary per feature is overhead you don't need yet. Boundaries also aren't a replacement for validating API responses. If you know a field can be null, handle it in the component and show a proper empty state. Save boundaries for the errors you didn't see coming.