Sub topic 11
Boundaries around lazy-loaded components
This chapter assumes you can write React function components, know that an error boundary is a class component with getDerivedStateFromError and componentDidCatch, and understand Promises and import(). You should also know which errors boundaries do not catch, and how to reset one.
Why lazy loading needs two wrappers
React.lazy lets you split a component into its own JavaScript chunk. The chunk downloads the first time React tries to render the component. That creates two situations your code has to handle:
- Waiting. The chunk is still downloading, so there is nothing to render yet.
- Failure. The download fails, or the module throws while it loads.
React gives each situation to a different tool. Suspense handles waiting. An error boundary handles failure. Neither does the other's job, so a lazy component normally sits inside both.
How lazy components behave
lazy takes a function that returns a Promise for a module with a default export. React calls the function the first time it renders the component.
import { lazy } from "react";
const Chart = lazy(() => import("./Chart"));When React renders <Chart /> and the Promise is still pending, the component suspends. React stops rendering that part of the tree and looks upward for the nearest Suspense boundary. It shows that boundary's fallback until the Promise resolves.
If the Promise rejects, React does not suspend. It throws the rejection reason during render, as if Chart had thrown the error itself. From there it follows the normal rule: the nearest error boundary above the component catches it.
If no error boundary exists, the error is uncaught and React unmounts the whole tree. A failed chunk download can therefore blank an entire app.
The standard pattern
Put the error boundary outside Suspense, and the lazy component inside it.
import { lazy, Suspense } from "react";
const Chart = lazy(() => import("./Chart"));
function Dashboard() {
return (
<ErrorBoundary fallback={<p>The chart failed to load.</p>}>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
);
}This is the ErrorBoundary class from the earlier chapter. Three things are worth noting about the nesting:
- The order matters. If you put
Suspenseoutside and the boundary inside, the lazy component is still inside the boundary's children, so the error is caught. The common convention is boundary outside because the boundary then also covers errors thrown by anything else inside theSuspensesubtree, and the loading state and the error state are clearly separate layers. Suspensenever catches errors. Without a boundary, a rejected import goes straight past it.- One boundary and one
Suspensecan cover several lazy components. TheSuspensefallback shows while any of them is pending.
Why chunk loads fail
Knowing the causes helps you pick the right fallback message and recovery.
| Cause | Typical symptom |
|---|---|
| Network drops or the user goes offline | Import rejects with a fetch or network error |
| A new deployment removed old chunk files | A user with an old page open gets a 404 for a chunk name that no longer exists |
| A CDN or server returns an HTML error page | The browser fails to parse it as JavaScript |
| The module throws while it evaluates | Import rejects with that error |
| The module has no default export | `lazy` fails because it cannot find a component to render |
The deployment case is the most common surprise in production. A user loads your app, you deploy a new build, and the user then clicks a link that needs a chunk with a hashed filename from the old build. The old file is gone. The error is not a bug in the user's session, and retrying the same import will not help. Reloading the page fetches the new entry file and the correct chunk names.
Recovery: retry versus reload
A boundary's fallback should offer a way out. For lazy loading there are two options, and which one works depends on the cause.
Retry the import. This helps with a temporary network failure. There is a catch: after a rejection, the lazy component keeps the failed result. React caches the outcome of the first call, so re-rendering the same lazy component does not run the import again. Resetting the boundary alone therefore re-throws the same error.
The workaround is to wrap the import in a function that retries, and to create the lazy component only once per attempt.
import { lazy } from "react";
function lazyWithRetry(load, retries = 2) {
return lazy(async () => {
let lastError;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return await load();
} catch (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));
}
}
throw lastError;
});
}
const Chart = lazyWithRetry(() => import("./Chart"));Here the retry loop lives inside the function that lazy calls, so React still sees a single Promise. It resolves if any attempt works and rejects after the last one. The delay grows with each attempt.
Reload the page. This helps when a deployment replaced the chunks. The fallback offers a button that reloads.
function ChunkErrorFallback() {
return (
<div role="alert">
<p>This part of the page could not be loaded.</p>
<button onClick={() => window.location.reload()}>Reload page</button>
</div>
);
}Reloading discards unsaved client state, so use it as the last step. A reasonable policy is automatic retries for network errors, then a reload button if they fail.
Do not reload automatically in a loop. If the failure is permanent, such as a server that is down, an automatic reload will repeat forever. If you do reload automatically, record the attempt in sessionStorage and allow it only once.
Combining with react-error-boundary
The react-error-boundary library works the same way here. Its resetKeys and resetErrorBoundary help when the failure is temporary and you create a fresh lazy component on retry.
import { lazy, Suspense, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
function loadChart() {
return lazy(() => import("./Chart"));
}
function Dashboard() {
const [Chart, setChart] = useState(() => loadChart());
return (
<ErrorBoundary
fallbackRender={({ resetErrorBoundary }) => (
<div role="alert">
<p>The chart failed to load.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)}
onReset={() => setChart(loadChart())}
>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
);
}When the user clicks "Try again", resetErrorBoundary clears the error and calls onReset. That handler replaces the cached failed component with a new lazy call. The boundary then renders again, the new component suspends, and the import runs a second time.
Creating lazy inside a component is normally a mistake, because every render makes a new component type and React discards its state. Here the value is stored in state and only replaced on reset, so it is stable between renders.
Choosing where to put the pair
Boundary placement from earlier chapters applies directly. Some guidelines specific to lazy code:
- Route level. Split by route and give each route its own
Suspenseand boundary pair, or one pair around the router outlet. A failed route then shows an error in the content area while navigation stays usable. - Heavy widgets. For a chart, editor, or map, wrap the widget alone. The rest of the page keeps working and the fallback is the size of the widget.
- Small components. Do not lazy-load tiny components. The extra request costs more than the code saves, and every lazy component adds a loading state and a failure state to design.
Give the Suspense fallback roughly the same size as the loaded content. Otherwise the layout jumps when the component arrives.
Common mistakes
- No boundary around lazy components. A failed import unmounts the whole app.
- Expecting
Suspenseto handle errors. It only handles waiting. - Resetting without replacing the lazy component. The cached rejection throws again immediately, so the retry button looks broken.
- Defining
lazyinside a component body without storing it. Each render creates a new type, so the component remounts and may reload repeatedly. - Named exports.
lazyexpects the module'sdefaultexport. For a named export, map it:lazy(() => import("./Chart").then((m) => ({ default: m.Chart }))). - Treating every import error alike. Deployment mismatches need a reload. Network blips may recover with a retry.
Summary
A lazy component has two states beyond "loaded": waiting and failed. Suspense covers waiting and an error boundary covers failure, so wrap lazy components in both, with the boundary outside. A rejected import is cached, so a retry has to create a new lazy component or retry inside the loader. Choose between retrying and reloading according to the cause.
Exercise
A user clicks "Try again" in your boundary's fallback after a chunk fails to load because of a brief network outage. The boundary resets, but the same error appears at once and no new network request is sent. Why does this happen, and how do you fix it?
Show answer
React caches the rejected result of the first call to the lazy loader, so re-rendering the same lazy component throws the cached error without running import() again. Fix it by creating a new lazy component on reset (for example, store it in state and replace it in onReset), or by retrying inside the function passed to lazy so the Promise only rejects after several attempts.
Exercise
You have <Suspense fallback={<Spinner />}><Chart /></Suspense> with no error boundary, and Chart is lazy. The import fails with a 404 after a deployment. What happens to the app, and what two changes make the failure recoverable?
Show answer
The rejection is thrown during render. Suspense does not catch errors, and there is no boundary, so React unmounts the whole tree and the user sees a blank page. Wrap the Suspense in an error boundary with a fallback, and make the fallback offer a page reload, because a 404 for a removed chunk will not succeed on retry but a reload fetches the new build's chunk names.