Sub topic 7
Handling chunk load failures with error boundaries
This chapter assumes you can write React function components, use useState, understand ES module import/export, and know how promises resolve or reject. It builds on React.lazy and Suspense from the earlier chapters.
Why a chunk can fail to load
React.lazy calls a dynamic import() the first time the component renders. That call is a network request for a chunk, and network requests fail. Common causes:
- The user goes offline or the connection drops mid-download.
- You deployed a new build, and the old chunk filename (for example
Chart-3f9a1c.js) no longer exists on the server. - A CDN or proxy returns an error page instead of JavaScript.
When this happens, the promise returned by import() rejects. Suspense only handles the pending state. It does not handle rejection. React treats the rejection as an error thrown while rendering, and without a handler the whole component tree unmounts and the user sees a blank page.
What an error boundary is
An error boundary is a class component that catches errors thrown by its descendants during rendering. It then renders a fallback UI instead of the crashed subtree. React has no function-component version of this feature. You need getDerivedStateFromError, which is a class static method.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}
// Usage
// <ErrorBoundary fallback={<p>Could not load this section.</p>}>
// <Suspense fallback={<p>Loading...</p>}>
// <Chart />
// </Suspense>
// </ErrorBoundary>getDerivedStateFromError runs after a descendant throws. It returns new state, and the next render shows this.props.fallback.
Order matters: boundary outside, Suspense inside
Place the error boundary outside Suspense. A boundary catches errors from components below it, so it must be an ancestor of the lazy component's Suspense. The two wrappers play different roles:
| Wrapper | Handles | Shows |
|---|---|---|
| `Suspense` | The chunk is still downloading | Loading fallback |
| `ErrorBoundary` | The chunk download rejected | Error fallback |
Letting the user retry
A static message leaves the user stuck. Adding a retry button is more useful, but there is a catch. React.lazy caches its result. Once the promise rejects, the lazy component stays in the failed state, and re-rendering it throws the same error again. Resetting the boundary alone is not enough.
A common fix is to wrap the import so that a failure triggers one or more fresh attempts before it gives up:
import { lazy } from 'react';
function lazyWithRetry(load, retries = 2) {
return lazy(() => attempt(load, retries));
}
function attempt(load, retries) {
return load().catch((error) => {
if (retries === 0) {
throw error;
}
return new Promise((resolve) => setTimeout(resolve, 500)).then(() =>
attempt(load, retries - 1)
);
});
}
const Chart = lazyWithRetry(() => import('./Chart'));Each retry calls import() again, which makes a new request. Some bundlers cache a failed dynamic import in the browser's module map, so a retry for the same URL may fail again. This is why retry helpers are a best effort, not a guarantee.
Recovering from a stale deploy
If the failure comes from a new deployment, retrying the old URL will never work, because that file is gone. The reliable recovery is to reload the page so the browser fetches the new index.html, which points to the new chunk names. You can do this from the error fallback:
import { ErrorBoundary } from './ErrorBoundary';
function ReloadMessage() {
return (
<div role="alert">
<p>This section could not be loaded.</p>
<button onClick={() => window.location.reload()}>Reload page</button>
</div>
);
}
export function SafeSection({ children }) {
return <ErrorBoundary fallback={<ReloadMessage />}>{children}</ErrorBoundary>;
}Reloading discards in-memory state, so use it as the last step, after a retry has failed.
Where to put boundaries
You can place one boundary at the top of the app, or several around independent sections.
- A single top-level boundary is a safety net. A failure anywhere replaces the whole app with the fallback.
- A boundary around each lazy section limits the damage. If the chart chunk fails, the rest of the dashboard keeps working.
Use both. The top-level boundary catches what you did not anticipate, and local boundaries keep optional features from taking down core ones.
Common mistakes
- Putting the boundary inside
Suspenseor inside the lazy component. It will not see the error from the lazy load, because the error is thrown by the lazy wrapper above its children. - Expecting
try/catchoruseEffectto catch it. Render-time errors fromlazyare not catchable that way. - Assuming a boundary catches event handler errors. It does not. Boundaries cover rendering, lifecycle methods, and constructors only.
- Logging nothing. Add
componentDidCatch(error, info)to the class and send the error to your monitoring service, so you can see how often chunk failures happen.
Exercise
A dashboard lazy-loads a Chart component. You wrap it as <Suspense fallback={<p>Loading...</p>}><ErrorBoundary fallback={<p>Failed</p>}><Chart /></ErrorBoundary></Suspense>. The user goes offline and the chunk request fails. Is this arrangement correct, and what should you change?
Show answer
The order is wrong in spirit and fragile in practice. The error boundary is inside Suspense, so while Chart is pending, Suspense shows its loading fallback, and the boundary only wraps the suspended child. The recommended structure is the ErrorBoundary outside and Suspense inside, so the boundary is clearly an ancestor of everything that can throw and the loading and error states are handled by separate layers. Swap them: <ErrorBoundary fallback={<p>Failed</p>}><Suspense fallback={<p>Loading...</p>}><Chart /></Suspense></ErrorBoundary>.
Exercise
Why does clicking a "Try again" button that only clears the error boundary's state often fail to fix a failed lazy component?
Show answer
React.lazy caches the rejected promise. Re-rendering the same lazy component reuses that cached failure and throws again. You need to create a fresh lazy attempt, for example with a retry wrapper that calls import() again, or reload the page when the cause is a stale deploy.