Sub topic 7
Handling chunk load failures with error boundaries
This chapter assumes you know React.lazy, Suspense, and class versus function components. It also assumes you are comfortable with promises and with how a bundler emits separate chunk files. By the end you will be able to catch a failed chunk download, show a useful message, and offer the user a real way to recover.
Why chunk loads fail
React.lazy wraps a dynamic import(). That call is a network request, and network requests fail. Common causes:
- The user's connection drops, or a mobile network times out.
- A browser extension or corporate proxy blocks the file.
- A new deployment replaced the old chunk files. Bundlers put a content hash in each file name, such as
Chart-a1b2c3.js. A user who loaded the app before the deploy still has the old entry file, which asks for a file the server no longer has. The server returns a 404 or an HTML error page. - The CDN returns a transient 5xx error.
In every case the promise returned by import() rejects. React.lazy passes that rejection to React as an error thrown during render. Suspense does not handle errors, so it does nothing here. The error moves up the tree until something catches it. If nothing does, React unmounts the whole tree and the user sees a blank page.
What an error boundary does
An error boundary is a class component that defines static getDerivedStateFromError, componentDidCatch, or both. When a descendant throws during rendering, the nearest boundary above it renders a fallback in place of its children.
Suspense and error boundaries cover opposite outcomes of the same operation:
| Outcome of loading | Handled by | Result |
|---|---|---|
| Still pending | `Suspense` | Shows the `fallback` prop |
| Resolved | Neither | Component renders normally |
| Rejected | Error boundary | Shows an error UI |
There is no function-component version of an error boundary in React itself. The class is required. Libraries such as react-error-boundary wrap it for you.
A minimal boundary
This is the boundary from the plan, with componentDidCatch added for logging.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error('Caught by boundary:', error, info.componentStack);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}getDerivedStateFromError runs during rendering, so it must be pure. It only records the error in state. componentDidCatch runs after the commit, so it is the place for side effects such as sending the error to a monitoring service.
Boundary placement: outside Suspense
Put the error boundary outside the Suspense boundary that wraps the lazy component:
import { lazy, Suspense } from 'react';
import { ErrorBoundary } from './ErrorBoundary';
const Chart = lazy(() => import('./Chart'));
export default function Dashboard() {
return (
<section>
<h1>Dashboard</h1>
<ErrorBoundary fallback={<p>Could not load the chart.</p>}>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
</section>
);
}The order matters because an error propagates upward. A boundary inside Suspense would never see the lazy component's rejection, because the lazy component is a child of that boundary only if it sits below it. With the boundary outside, the sequence is:
You can use one boundary per lazy section, or one boundary per route or page. A small boundary keeps the rest of the page alive when one widget fails. A large boundary is simpler, but one broken chunk replaces everything inside it. Choose the size by asking what the user can still do when this piece is missing.
Recovering: why "try again" is not trivial
A useful error UI offers a retry. The obvious approach is a button that clears the boundary's error state. For lazy components this does not work, and the reason matters.
React.lazy calls your loader once and remembers the outcome. If the promise rejected, the lazy component stays rejected. Clearing the boundary's state re-renders the same lazy component, which throws the same stored error immediately. No new request is made.
There are two working strategies.
Strategy 1: create a fresh lazy component per attempt
Keep one lazy component per attempt number, and use the attempt number as a key on the boundary. A new key remounts the boundary with its error state cleared.
import { lazy, Suspense, useState } from 'react';
import { ErrorBoundary } from './ErrorBoundary';
const loadChart = () => import('./Chart');
const attempts = new Map();
function getChart(attempt) {
if (!attempts.has(attempt)) {
attempts.set(attempt, lazy(loadChart));
}
return attempts.get(attempt);
}
export default function ChartSection() {
const [attempt, setAttempt] = useState(0);
const Chart = getChart(attempt);
const fallback = (
<div role="alert">
<p>Could not load the chart.</p>
<button onClick={() => setAttempt((n) => n + 1)}>Try again</button>
</div>
);
return (
<ErrorBoundary key={attempt} fallback={fallback}>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
);
}The Map lives at module level so each attempt's lazy component keeps a stable identity across renders. Creating lazy(...) directly inside a component body would produce a new component type on every render and reset its state each time.
Whether the second attempt hits the network depends on the browser. Some browsers have remembered a failed module URL for the rest of the page's life. If retries keep failing for the same file, fall back to strategy 2.
Strategy 2: reload the page
For a stale deployment, retrying the old file name cannot succeed. The reliable fix is a full reload, which fetches the new entry file and the new chunk names.
export function reloadFallback() {
return (
<div role="alert">
<p>A new version is available.</p>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
);
}Unsaved form data is lost on reload. Warn the user, or save the data first.
Retrying the import automatically
Brief network glitches often clear in a second. You can retry inside the loader, so the user never sees the error:
import { lazy } from 'react';
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function importWithRetry(load, retries = 2, delay = 500) {
try {
return await load();
} catch (error) {
if (retries === 0) throw error;
await wait(delay);
return importWithRetry(load, retries - 1, delay * 2);
}
}
export const Chart = lazy(() => importWithRetry(() => import('./Chart')));This waits 500 ms, then 1000 ms, before giving up and letting the rejection reach the error boundary. Keep the retry count small. Each retry extends the time the user sees the loading fallback, and a 404 from a stale deploy will never succeed.
Detecting chunk errors specifically
Not every error is a chunk error. A bug in your component also reaches the boundary. Showing "Reload the page" for a real bug can create a loop. You can check the error before choosing a response:
export function isChunkLoadError(error) {
const message = error && error.message ? error.message : '';
return (
(error && error.name === 'ChunkLoadError') ||
/Loading chunk|Loading CSS chunk|dynamically imported module|Importing a module script failed/i.test(
message
)
);
}The error name and message are not standardized. webpack uses ChunkLoadError. Chrome reports "Failed to fetch dynamically imported module". Firefox and Safari word it differently. Treat this check as a heuristic and test it in the browsers you support.
To avoid a reload loop, reload at most once per session:
export function reloadOnce() {
const key = 'chunk-reload-attempted';
if (sessionStorage.getItem(key)) {
return false;
}
sessionStorage.setItem(key, '1');
window.location.reload();
return true;
}If reloadOnce() returns false, show a static message that tells the user to check their connection. Clear the flag after a successful load if you want to allow a later reload.
What error boundaries do not catch
| Situation | Caught? | What to do instead |
|---|---|---|
| Rejected `import()` inside `React.lazy` | Yes | Boundary outside `Suspense` |
| Error thrown while rendering a child | Yes | Same boundary |
| Error inside an event handler | No | Use `try/catch` in the handler |
| Error in `setTimeout` or a promise you started yourself | No | Catch it and store it in state |
| An `import()` you call directly in an event handler or effect | No | Use `.catch()` on the promise |
| Error thrown by the boundary's own `render` | No | A boundary higher up catches it |
| Server-side rendering | No | Handle in the server rendering API |
The last point on the direct import() row matters for preloading. A preload that fails should usually be ignored, because the real load will report the error. Write loadSettings().catch(() => {}) in a hover handler to avoid an unhandled rejection warning.
Boundaries and nested structure
Boundaries nest. An error goes to the closest boundary above the thrower. A common layout has two levels:
- A page-level boundary that shows a full-page error with a reload button.
- Smaller boundaries around optional widgets, such as a chart or a comments panel, that show a short inline message.
If the inline boundary's fallback itself throws, the error moves up to the page-level boundary. Keep fallbacks simple so they cannot fail.
In development, React shows its error overlay even when a boundary catches the error. Judge the behavior by what the page renders after dismissing the overlay, or by running a production build.
Testing the failure path
Test the failure UI before users find it for you:
- In browser developer tools, open the Network tab and block the request URL for one chunk. Reload, then trigger the lazy component.
- Set throttling to "Offline" after the page loads, then navigate to a lazy route.
- In a unit test, mock the loader to reject:
lazy(() => Promise.reject(new Error('boom'))). Render it inside your boundary andSuspense, and assert that the error message appears.
For the test in step 3, React logs the caught error to the console. Silence the console in that test so the output stays readable.
Exercise
You wrap a lazy component like this: <Suspense fallback={<Spinner />}><ErrorBoundary fallback={<Oops />}><Chart /></ErrorBoundary></Suspense>. The chunk request fails, but the page goes blank instead of showing Oops. What is wrong, and how do you fix it?
Show answer
The nesting is reversed, but the more important point is the cause of the blank page. With the boundary inside Suspense, the rejection still reaches the boundary, so Oops would normally appear. A blank page means the error is thrown by something outside the boundary. The structure is fragile, though, because the error boundary should be the outer layer so that any load error from the lazy subtree, including from other lazy children added later, is caught by it. Fix it by writing <ErrorBoundary fallback={<Oops />}><Suspense fallback={<Spinner />}><Chart /></Suspense></ErrorBoundary>. If the page is still blank, check that the boundary is a class component with getDerivedStateFromError and that Oops itself does not throw.
Exercise
A user clicks "Try again" in your error UI, which only sets the boundary's error state back to null. The same error appears at once and no network request is made. Why, and what are two ways to make the retry work?
Show answer
React.lazy stores the rejected result, so rendering the same lazy component throws the stored error again without calling the loader. Either create a new lazy component for each attempt, with a module-level cache keyed by attempt number, and change the boundary's key so it remounts, or call window.location.reload(). Reloading is the better choice when the cause is a stale deployment, because the old chunk file names no longer exist.
Exercise
Which of these errors will an error boundary catch? (a) a rejected import() passed to lazy, (b) a fetch failure inside an onClick handler, (c) a TypeError thrown in a child's render function.
Show answer
(a) and (c). Both occur during rendering. The failure in (b) happens in an event handler outside the render phase, so you must handle it with try/catch or .catch() and show the result through state.