Sub topic 7
Where to place boundaries
This chapter assumes you can write the class-based ErrorBoundary from the earlier chapter. It takes a fallback prop and shows it after a descendant throws during rendering. It also assumes you know which errors boundaries do not catch. Here the question is where in the component tree to put them.
Why placement matters
A boundary catches errors from components below it and replaces that whole subtree with its fallback. The boundary's position therefore sets two things:
- The blast radius. Everything inside the boundary disappears when any part of it throws.
- The fallback's footprint. The fallback appears exactly where the subtree was. A boundary around a whole page produces a full-page message. A boundary around a small widget produces a small message in the widget's place.
Two extremes show the trade-off:
- One boundary at the root. Any rendering error blanks the whole app. This is better than a white screen with no message, but a broken avatar menu still takes down the checkout form.
- A boundary around every component. Failures stay small, but the page can fill with "Something went wrong" boxes. Most of these share a single cause, such as one failed request, so users see the same error many times. The code is also noisier, and you have many more fallbacks to design and test.
Good placement sits between these. Put boundaries around parts of the UI that can fail independently and that the user can still work without.
A layered approach
Most apps do well with boundaries at three levels. Each level catches what the one below it misses.
App level
One boundary near the root is the last line of defense. It catches anything the lower boundaries do not, including errors in the layout itself. Its fallback should be simple and self-contained. It should not depend on the router, the theme provider, or application state, because any of those may be what failed. A plain message and a "Reload page" button are enough.
Route level
A boundary around each route's content keeps navigation working when one page breaks. The header and the nav links live outside this boundary, so the user can click to another page. If the boundary sits inside the router and the layout, navigating away also gives you a natural moment to reset it. Resetting is covered in the recovery chapter.
Widget level
Wrap independent sections of a page, such as a chart, a comments list, a recommendations panel, or an embedded third-party widget. If the page is still useful without that section, give the section its own boundary. Third-party code and components that render data you do not control are the best candidates, because they have the most ways to fail.
Here is a page that uses all three levels:
import { ErrorBoundary } from "./ErrorBoundary";
import { Header } from "./Header";
import { Chart } from "./Chart";
import { CommentList } from "./CommentList";
function PageMessage() {
return (
<section>
<h2>This page could not be shown</h2>
<p>Use the navigation to go somewhere else.</p>
</section>
);
}
function Inline({ children }) {
return <p className="inline-error">{children}</p>;
}
export function App() {
return (
<ErrorBoundary
fallback={
<div role="alert">
<p>The app hit an unexpected problem.</p>
<button onClick={() => window.location.reload()}>Reload page</button>
</div>
}
>
<Header />
<ErrorBoundary fallback={<PageMessage />}>
<main>
<ErrorBoundary fallback={<Inline>The chart is unavailable.</Inline>}>
<Chart />
</ErrorBoundary>
<ErrorBoundary fallback={<Inline>Comments could not be loaded.</Inline>}>
<CommentList />
</ErrorBoundary>
</main>
</ErrorBoundary>
</ErrorBoundary>
);
}If Chart throws while rendering, only the chart is replaced. The comments, the header, and the rest of the page keep working. If Header throws, the app-level boundary catches it, since the header sits outside the route boundary.
How the nearest boundary is chosen
When a component throws, React looks upward from that component for the closest boundary and hands the error to it. Three consequences follow:
- A boundary cannot catch its own errors. If the boundary's
rendermethod throws, or its fallback throws, the error goes to the next boundary above it. This is why the app-level boundary exists, and why fallbacks must be simple. A fallback that readserror.response.data.messagecan itself crash whenresponseis undefined. - A boundary must be above the thing that throws. Putting a boundary inside
Chartdoes nothing for errors thrown byChart's own render. The boundary has to be a parent ofChart. - Only one boundary reacts. The outer boundaries are not triggered when an inner one catches the error. They stay in their normal state.
A common mistake is wrapping a component's return value in the same component:
// Does not work: the boundary is rendered by Profile,
// so an error thrown by Profile itself is not inside it.
function Profile({ user }) {
return (
<ErrorBoundary fallback={<p>Oops</p>}>
<h1>{user.name.first}</h1>
</ErrorBoundary>
);
}If user is undefined, Profile throws while evaluating user.name, before the boundary is ever created. Place the boundary in the parent that renders <Profile />.
Deciding where a boundary belongs
For each candidate subtree, ask these questions:
- Can the rest of the page work without it? If yes, it is a good boundary candidate. If the page makes no sense without it, such as the main form on a form page, let the failure move up to the route level.
- Does it fail independently? Two components that read the same data fail together. Give them one shared boundary, not two. Otherwise the user sees two identical error boxes for one cause.
- What can the user do next? The fallback should offer a way forward. A route-level fallback can point to other pages. A widget-level fallback can say what is missing and, once you add reset, offer a retry.
- Is the code risky? Third-party widgets, user-generated content, and rich renderers (markdown, charts, maps) deserve tighter boundaries than simple layout components.
The following table summarizes the trade-offs.
| Level | Good for | What the user sees on failure | Risk of overuse |
|---|---|---|---|
| App | Last-resort catch, including layout errors | Full-page message, reload button | Everything disappears for any error |
| Route | Keeping navigation alive | Page area replaced, header and nav remain | Few. Usually worth having on every route |
| Widget | Independent, optional sections | One small message in place of the widget | Many similar messages, more fallbacks to maintain |
| Per item in a list | Items rendered from untrusted data | One broken row | A long list of repeated errors if every row fails the same way |
Boundaries inside lists
When a list renders items from data you do not control, one malformed record can break the whole list. A boundary around each item limits the damage to one row:
import { ErrorBoundary } from "./ErrorBoundary";
import { CommentCard } from "./CommentCard";
export function CommentList({ comments }) {
return (
<ul>
{comments.map((comment) => (
<li key={comment.id}>
<ErrorBoundary fallback={<span>This comment could not be shown.</span>}>
<CommentCard comment={comment} />
</ErrorBoundary>
</li>
))}
</ul>
);
}The key goes on the outermost element returned from map, here the li. This pattern fits cases like user-submitted content, where a bad record is plausible. It is not needed for data your own code has already validated. If the failure is more likely to affect every row, such as a bug in CommentCard itself, a single boundary around the list gives a cleaner result than fifty identical messages.
State is lost when a boundary shows its fallback
When a boundary switches to its fallback, React unmounts the subtree it was showing. Local state inside that subtree is discarded, including form input and scroll positions. When the boundary later resets and renders its children again, they mount fresh.
This affects placement. A boundary around a large form means one failing field component wipes everything the user typed. If one part of a form is risky, such as a rich-text preview, wrap only that part and keep the inputs outside the boundary.
import { useState } from "react";
import { ErrorBoundary } from "./ErrorBoundary";
import { MarkdownPreview } from "./MarkdownPreview";
export function PostEditor() {
const [text, setText] = useState("");
return (
<form>
<textarea value={text} onChange={(event) => setText(event.target.value)} />
<ErrorBoundary fallback={<p>The preview is unavailable.</p>}>
<MarkdownPreview source={text} />
</ErrorBoundary>
</form>
);
}The text lives in PostEditor, which is outside the boundary. If MarkdownPreview throws on some input, the preview is replaced but the user's text stays, so they can fix it.
Common mistakes
- Only one boundary at the root. Any error blanks the entire app.
- A boundary in the wrong place. It sits inside the component that throws, so it never sees the error.
- Many boundaries for one failure. Components that share a cause need a shared boundary.
- Complex fallbacks. A fallback that fetches data or reads context may crash and push the error upward.
- Silent boundaries. The user sees a fallback, but nobody on the team learns about the error.
Exercise
A dashboard page has a header with navigation, a sales chart, and a form where users type notes. The chart reads from an unreliable third-party library. Where would you place error boundaries, and why not put the chart and the form under the same one?
Show answer
Put one app-level boundary at the root as a last resort, and one route-level boundary around the dashboard content so the header and navigation stay usable. Then put a widget-level boundary directly around the chart, as a parent of the chart component. The chart is optional and risky, so a failure there should replace only the chart. Keeping the form outside the chart's boundary means a chart error does not unmount the form and discard the user's typed notes. Sharing one boundary would couple two independent parts of the page.