What You'll Learn
- 1Distinguish rendering errors from event-handler and async failures
- 2Implement an error boundary with derived state and a reporting hook
- 3Choose boundary placement that keeps the rest of the page usable
- 4Reset a boundary safely after a retry or a route change
What a boundary catches, and what it does not
An error boundary is a component that stops a rendering failure from unmounting the entire page. When an error is thrown while React renders a subtree, the nearest boundary above it catches the error, runs its fallback instead, and leaves the rest of the tree mounted. Without one, React removes the whole root, and the user is staring at a blank screen with no explanation.
The catch list is narrower than most developers expect. Boundaries catch errors thrown during rendering, in lifecycle methods, and in constructors. They do not catch errors inside event handlers, where a try block is still the right tool; errors in asynchronous callbacks such as a resolved promise continuation; errors thrown in server-side code outside React; or errors caused by the boundary's own fallback. That last category is how teams accidentally ship a white screen again after already writing a boundary.
// Caught by the boundary above this component
function Profile({ user }) {
return <h1>{user.name.toUpperCase()}</h1>;
}
// Not caught: needs a try block inside the handler
function SaveButton({ onSave }) {
const handleClick = () => {
try {
onSave();
} catch (err) {
console.error(err);
}
};
return <button type="button" onClick={handleClick}>Save</button>;
}
Building a reusable boundary
Boundaries must be class components, because the two lifecycle methods that implement them do not exist in function components and no hook wraps them. getDerivedStateFromError runs during render and should return the state update that switches the tree to the fallback; componentDidCatch runs after the commit and is where side effects such as logging belong.
import { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, phase: 'ok' };
}
static getDerivedStateFromError(error) {
return { error, phase: 'failed' };
}
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
reset = () => {
this.setState({ error: null, phase: 'ok' });
};
render() {
const { error, phase } = this.state;
if (phase === 'failed') {
if (typeof this.props.fallback === 'function') {
return this.props.fallback({ error, reset: this.reset });
}
return (
<div className="boundary-fallback" role="alert">
<h2>This section could not be displayed</h2>
<p>{error?.message}</p>
<button type="button" onClick={this.reset}>Try again</button>
</div>
);
}
return this.props.children;
}
}
Two design choices pay off later. Passing a render function as the fallback lets each call site decide how much context to show, and exposing a reset function turns a dead end into a retry the user can attempt.
Placement is a product decision
One boundary at the root means any failure costs you the whole page. Boundaries too far down leave users with a broken shell and no way to navigate. The useful granularity mirrors what the user perceives as independent.
| Placement | Effect when it fires | Use for |
|---|---|---|
| Root, above the router | Blank page with a reload link | Truly unrecoverable configuration errors |
| Around the layout and navigation | Content fails, shell survives | Keeping menus and search available |
| Around a widget or panel | One region shows a fallback | Dashboards, carousels, third-party embeds |
| Around a list or table | Row-level failure degrades gracefully | Data grids with complex cell renderers |
| Around a lazy route | Navigation continues to work | Code-split pages loaded on demand |
A practical rule is to add a boundary above anything that renders data you do not control, including user-generated content, third-party scripts, and remote configuration.
Reporting without creating new failures
A boundary that logs to the console in production is a boundary that lost half its value. Send the error and the component stack to a monitoring service, but do it defensively: a reporter that throws, or one that triggers a state update in the component that just failed, starts a second failure while you are still handling the first.
function reportError(error, info, context) {
const payload = {
message: error && error.message ? error.message : 'Unknown error',
stack: error && error.stack ? error.stack : '',
componentStack: info && info.componentStack ? info.componentStack : '',
route: typeof window === 'undefined' ? 'ssr' : window.location.pathname,
context,
};
navigator.sendBeacon?.(
'/api/client-errors',
new Blob([JSON.stringify(payload)], { type: 'application/json' })
);
}
class ReportingBoundary extends Component {
componentDidCatch(error, info) {
reportError(error, info, { boundary: this.props.name });
}
render() {
return this.props.children;
}
}
sendBeacon is a good fit because it survives the page being torn down shortly after the error. Sample the payload rather than shipping every field of the user's state, and scrub anything that could contain personal data before it leaves the browser.
Resetting without leaving stale state
A boundary that catches an error keeps rendering the fallback until its state is cleared, and clearing it does not by itself fix the underlying problem. If the error came from a prop, retrying immediately reproduces it, which looks like a broken button to the user.
The reliable pattern is a reset key: a value that changes when something genuinely different happens, such as a route change or a new record id. When the key changes, remount the boundary by rendering it with the new key, which resets both the boundary and the failing subtree together.
function RouteBoundary({ locationKey, children }) {
return (
<ErrorBoundary key={locationKey} fallback={({ reset }) => (
<div role="alert">
<p>Something went wrong on this page.</p>
<button type="button" onClick={() => window.location.reload()}>Reload</button>
</div>
)}>
{children}
</ErrorBoundary>
);
}
Also consider that a retry may succeed only after the user does something, such as signing in again or clearing a filter. Offer that next step in the fallback copy rather than assuming the button will be enough.
Fallbacks that respect the product
The fallback is part of the interface, and a generic apology wastes the only moment when you have the user's full attention. A good fallback answers three questions without requiring the user to open a support ticket: what failed, whether their work is safe, and what they can do next. Those answers differ by surface. A collapsed chart widget can say that the chart is unavailable and offer a refresh, while a broken checkout step must reassure the user that nothing was charged and provide a way back to the cart.
Degradation in levels is worth designing for. The first level keeps surrounding chrome intact, so navigation and search still work. The second replaces the failing region with cached data or a static summary. The third is the full-page fallback, and it should be rare enough that a user seeing it has genuinely hit a broken deployment rather than a rendering bug in one widget.
Think about what the boundary cannot see as well. If the failing subtree held unsaved user input, the fallback destroys it. Capture drafts to storage before mounting risky regions, or choose a boundary placement that leaves the form mounted while the surrounding panel fails. That single consideration separates a fallback that feels competent from one that costs the user their work.
Event handlers, async code, and server rendering
Because boundaries do not watch event handlers, wrap risky logic yourself, and translate the failure into state that the UI can display. Async work needs the same treatment: a rejected promise inside useEffect is invisible to any boundary, so catch it and set an error field in state, or let a data library surface the rejection.
On the server, boundaries still catch render errors, but the fallback is rendered into the initial HTML and there is no browser to reload. Keep the server fallback minimal, log the error on the server as well, and make sure the client hydrates without immediately re-throwing the same failure. A hydration mismatch caused by different fallback markup on each side is a separate problem, and it is solved by rendering the same minimal fallback in both environments.
Common Mistakes
Expecting a boundary to catch a rejection from a fetch started in an effect
Fix: Catch the rejection in the effect or in the data layer and store an error field in state
Wrapping the entire application in one boundary so any bug blanks the page
Fix: Add boundaries at widget and route level, keeping only the root as a last resort
Resetting boundary state on retry while the failing prop is unchanged
Fix: Key the boundary on a value that changes when the underlying data changes
Throwing inside componentDidCatch or inside the fallback render
Fix: Guard the reporting path and keep the fallback markup as simple as possible
Best Practices
- Place a boundary above every component that renders untrusted or remote data
- Pass a name prop so your reports identify which boundary caught the error
- Offer a concrete next step in the fallback: reload, sign in again, or return home
- Keep fallback markup free of hooks, data fetching, and complex styling
- Log component stacks in development; they are the fastest route to the failing render
Key Takeaways
- Boundaries catch rendering and lifecycle errors, not event handlers or async rejections
- Implementation requires the two class lifecycle methods: derived state for render, and catch for logging
- Placement decides how much of the page survives, so mirror the granularity users perceive
- Reporting must never throw or update state, or you start a second failure
- Key a boundary on a route or record value so retries actually remount the failing subtree