Sub topic 11
Boundaries around lazy-loaded components
This chapter assumes you can write a class-based boundary or use react-error-boundary, and that you know the basics of Suspense. It covers how a boundary and Suspense work together around code that loads on demand.
Why lazy components need two wrappers
lazy() delays loading a component's code until it first renders. That loading can end in three ways:
- The import is still running. The component is not ready.
- The import succeeds. The component renders.
- The import fails, for example because of a network error or a missing file after a deploy. The component can never render.
Suspense handles the first case. React pauses rendering of that subtree and shows the fallback prop. Suspense does nothing for the third case. A failed import rejects the promise, and React rethrows that rejection during rendering. Without an error boundary above it, the error unmounts the whole tree, as described in the first chapter.
So each lazy component needs both wrappers, with the boundary on the outside.
import { lazy, Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
const Chart = lazy(() => import("./Chart"));
export default function Dashboard() {
return (
<ErrorBoundary fallback={<p>The chart failed to load.</p>}>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
);
}The import path must point to a module with a default export that is a component. You can use your own class-based boundary instead of the library one. The wrapping is identical.
Why the order matters
The boundary goes outside Suspense for a practical reason. React looks upward for the nearest boundary when something throws. A rejected import is an error, so React looks for an error boundary. If the boundary sat inside Suspense, it would not be an ancestor of the suspended Chart in the way you want. Put the boundary on the outside and you also get one clear place to decide what the user sees when loading fails.
You can share one boundary across several lazy components. Wrap each in its own Suspense so one slow component does not hide the others. Give each lazy component its own boundary if you want a failure in one to leave the others visible.
Retrying a failed import
A reset button does not fix a failed lazy() by itself. React remembers the rejected result for that lazy component. Re-rendering it throws the same error again without making a new request.
One fix is to retry inside the loader, so the failure never reaches React unless both attempts fail.
import { lazy } from "react";
function lazyWithRetry(load) {
return lazy(() => load().catch(() => load()));
}
const Chart = lazyWithRetry(() => import("./Chart"));This helps with brief network drops. It does not help when the chunk file no longer exists, which happens when a new deploy removes old filenames while a user still has the old page open. For that case, offer a full reload in the fallback.
function ChunkFallback() {
return (
<div role="alert">
<p>This part of the page could not be loaded.</p>
<button onClick={() => window.location.reload()}>Reload page</button>
</div>
);
}Pass it with <ErrorBoundary FallbackComponent={ChunkFallback}>. Reloading fetches the new HTML, which points at the current chunk names.
Common mistakes
| Mistake | Result |
|---|---|
| `Suspense` with no boundary above it | A failed import unmounts the whole app. |
| Declaring `lazy()` inside a component body | A new lazy component is created on every render, so it reloads and loses state. Declare it at module level. |
| One large boundary around the whole app for all lazy routes | A single failed chunk replaces every page with the error fallback. |
| Lazy component without a default export | The import "succeeds" but rendering fails, and the boundary shows the fallback. |
Exercise
A dashboard loads a lazy Chart wrapped only in <Suspense fallback={<p>Loading…</p>}>. A user goes offline before opening the dashboard, and the whole page goes blank. Why did that happen, and what is the smallest change that keeps the rest of the page visible?
Show answer
The failed import rejects, and React rethrows the rejection while rendering. Suspense only handles the pending state, so no boundary catches the error and React unmounts the entire tree. Wrap the Suspense element in an error boundary, for example <ErrorBoundary fallback={<p>The chart failed to load.</p>}>. Then only the chart area shows the fallback.