Sub topic 4
Showing a useful fallback
This chapter assumes you can write the class-based boundary from the previous chapter. It also assumes you know basic JSX, props, and how getDerivedStateFromError stores an error in state. Here the focus is on what the boundary renders after it catches an error.
What the fallback is
When a boundary catches an error, it stops rendering its children and renders the fallback in their place. The fallback is ordinary React output. It can be a string, an element, or a full component tree. The boundary does not care what it is, but your users do.
A useful fallback does four things:
- It says what failed, in terms the user understands.
- It shows how much of the page is affected.
- It offers a next step.
- It does not make the rest of the page worse.
An empty <div> or a raw stack trace does none of these. A blank region looks like a loading glitch. A stack trace tells a user nothing and may expose internals.
Letting the boundary accept more than an element
The earlier chapter passed a ready-made element through a fallback prop. That works for static messages. When the fallback needs to show the error, a render function is more flexible. The boundary below accepts either form and has a default.
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
console.error(error, info.componentStack);
}
render() {
if (!this.state.hasError) {
return this.props.children;
}
const { fallback } = this.props;
if (typeof fallback === "function") {
return fallback({ error: this.state.error });
}
if (fallback !== undefined) {
return fallback;
}
return <p role="alert">Something went wrong.</p>;
}
}The state uses a separate hasError flag instead of checking error !== null. JavaScript lets code throw any value, including null or undefined. With a null check, throw null would be stored as "no error" and the boundary would try to render the broken children again.
A fallback sized to the failure
A fallback should match the size of what it replaces. A failed order list should not take over the whole screen. A failed app shell needs a full-page message because nothing else is left to show.
const isDev = process.env.NODE_ENV !== "production";
function errorText(error) {
return String(error?.message ?? error);
}
export function InlineFallback({ title, error }) {
return (
<div
role="alert"
style={{ minHeight: 120, padding: 16, border: "1px solid #b00020" }}
>
<p>
<strong>{title}</strong>
</p>
<p>The rest of the page still works. Try again later.</p>
{isDev && <pre>{errorText(error)}</pre>}
</div>
);
}
export function PageFallback({ error }) {
return (
<main role="alert" style={{ padding: 32 }}>
<h1>Something went wrong</h1>
<p>We could not display this page.</p>
<a href="/">Go to the home page</a>
{isDev && <pre>{errorText(error)}</pre>}
</main>
);
}You then pick the fallback where you place the boundary:
import { ErrorBoundary } from "./ErrorBoundary";
import { InlineFallback, PageFallback } from "./fallbacks";
function App() {
return (
<ErrorBoundary fallback={({ error }) => <PageFallback error={error} />}>
<Header />
<ErrorBoundary
fallback={({ error }) => (
<InlineFallback title="We could not load your recent orders." error={error} />
)}
>
<RecentOrders />
</ErrorBoundary>
</ErrorBoundary>
);
}If RecentOrders throws, the inner boundary catches it. The header and the rest of the page stay visible. If Header throws, the outer boundary catches it and shows the page-level message. Choosing where these boundaries go is a design question of its own, covered in a later chapter.
Writing the message
The text in a fallback matters as much as the code. Some guidelines:
- Name the feature, not the exception. "We could not load your recent orders" is better than "TypeError: Cannot read properties of undefined".
- Say what still works. A line like "The rest of the page still works" tells users they do not need to start over.
- Offer one clear action. That might be a link home, a contact address, or a retry button. Retry needs a reset mechanism, which a later chapter covers.
- Avoid blame and jargon. Do not write "Fatal error" or "Invalid state".
Do not show raw error messages in production
An error's message can include internal names, file paths, query text, or user data. It is useful to a developer and risky to a visitor. The example above shows the message only when NODE_ENV is not "production". In production, send the details to a logging service and show the user a plain sentence. Error reporting is covered in its own chapter.
Keeping the layout stable
A fallback that is much smaller than the content it replaces makes the page jump. Other elements shift upward, and the user may lose their place. Some ways to limit this:
- Give the fallback a
minHeightclose to the normal height of the region, asInlineFallbackdoes. - Keep the fallback inside the same container, so grid and flex rules still apply.
- For full-page fallbacks, render the same outer layout wrapper if it is safe to do so (see the next section).
Accessibility
Users of screen readers cannot see that a region changed. Two small additions help.
role="alert"makes assistive technology announce the fallback text when it appears. Use it on the fallback's outermost element.- Keep the message in real text and real elements. A message drawn into an image or a canvas cannot be read aloud.
If the fallback includes a button or link, make sure it can be reached with the keyboard. Native <a> and <button> elements do this by default.
Keep the fallback simple and independent
The fallback runs in the same React tree as the failure. If it throws, the error moves to the next boundary up. In the worst case there is no outer boundary, and the whole tree unmounts, which is the problem boundaries are meant to prevent. A good fallback has few ways to fail.
Watch for these dependencies in a fallback:
| Dependency | Risk | Safer choice |
|---|---|---|
| Router `Link` | Throws if the boundary sits above the router provider | Plain `<a href>` in app-level fallbacks |
| Theme or i18n context | The provider may be the part that failed | Hard-coded English text and inline styles for the outermost fallback |
| Data from the failed component | Likely to be the cause of the error | Static text only |
| Heavy child components | More code that can throw | Short markup |
An inner, feature-level fallback can use the app's design system and translations, because the providers sit above it and are working. Only the outermost fallback needs to be nearly dependency-free.
Matching fallback types to situations
| Situation | Fallback | Example |
|---|---|---|
| Optional widget (recommendations, ads) | Nothing, or a one-line note | `fallback={null}` |
| Core section (order list, editor) | Inline message with the feature name | `InlineFallback` |
| App shell or route | Full-page message with a link out | `PageFallback` |
fallback={null} is a legitimate choice for decorative or optional content, but only if the failure is still reported. Silently hiding errors is how a feature breaks for weeks without anyone noticing. Notice that with this chapter's boundary, fallback={null} renders null, not the default message, because only undefined triggers the default.
Common mistakes
- Using the same generic fallback everywhere, so users cannot tell which part failed.
- Showing
error.messageorcomponentStackto end users. - Returning a fallback much shorter than the content, which makes the page jump.
- Building the outermost fallback from components that depend on providers that might themselves fail.
- Using
nullas a fallback without logging the error elsewhere.
Exercise
A boundary wraps a Comments section. When Comments throws, the page shows a small red box with the text "TypeError: Cannot read properties of undefined (reading 'map')". Name two problems with this fallback and describe how you would fix each.
Show answer
First, it exposes a raw error message to users, which is unhelpful and may leak internals. Fix it by showing a plain sentence such as "We could not load the comments" and showing the message only in development (or logging it instead). Second, it does not say what still works or what to do next. Fix it by adding a line like "The rest of the page still works" and an action such as a link or a retry button. Giving the box a minHeight close to the comments section's normal height and adding role="alert" would also improve layout stability and accessibility.
Exercise
Why does the boundary in this chapter use a hasError flag instead of checking this.state.error !== null?
Show answer
JavaScript code can throw any value, including null or undefined. If a component threw null, the stored error would be null, a null check would treat that as "no error", and the boundary would render the broken children again. A separate boolean records that an error happened regardless of the thrown value.