Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React.lazy and Code Splitting: Route Chunks, Preloading, and Suspense

Where the split points belong, how to preload on intent, and how to recover when a stale chunk 404s after a deployment.

~5 min readReact
#React#Performance#Bundling
3D illustration of a monolithic JavaScript bundle splitting into on-demand lazy route chunks loaded inside Suspense boundaries

Quick Summary

React.lazy turns a dynamic import() into a component. The module is not fetched until React actually renders the element, at which point the returned promise suspends the nearest <Suspense> boundary until the chunk arrives. That is the whole mechanism: no router integration required, no build configuration beyond a bundler that understands import(), and no wrapper library.

What it does not do is decide where the split points belong. Splitting every component produces dozens of small requests and a waterfall; splitting nothing ships a single bundle that must be downloaded, parsed, and executed before the first pixel. The useful pattern is route-level chunks, plus a small number of genuinely heavy widgets — an editor, a chart library, a video player, a map — that most visitors never open.

The subtle failure is not the missing chunk, it is the stale one. A visitor with an old HTML document still open after a deployment asks for a hash-named chunk that no longer exists, gets a 404, and sees a blank screen unless an error boundary catches the failure and reloads.

Basic Syntax & Signature

tsx
import { lazy, Suspense } from "react"; // load must return a promise resolving to a module with a default export. const HeavyChart = lazy(() => import("./HeavyChart")); export function Dashboard() { return ( <Suspense fallback={<p>Loading chart…</p>}> <HeavyChart data={data} /> </Suspense> ); }

The dynamic import is a function, not a value, so it is called when React first renders the lazy element and the promise is cached by React after it resolves. A named export needs a mapping layer:

tsx
const Editor = lazy(() => import("./Editor").then((mod) => ({ default: mod.NamedEditor })) );

Where you place the boundary determines what the user sees while the chunk loads. One boundary high in the tree shows a whole-page fallback; several boundaries show partial UI:

tsx
function Page() { return ( <main> <Header /> <Suspense fallback={<Skeleton rows={3} />}> <Feed /> </Suspense> <Suspense fallback={<Skeleton rows={1} />}> <Recommendations /> </Suspense> </main> ); }

React 19 adds resource hints to react-dom for the network side of the same problem: preload, preinit, prefetchDNS, and preconnect let a component declare what it will need before it renders.

Key Comparison Table

ApproachWhen the code loadsGranularityCost
Static importWith the parent bundleNoneLargest initial bundle
React.lazy per routeOn first navigation to the routeRouteOne chunk per route
React.lazy per widgetOn first render of the widgetComponentOne chunk per widget
Conditional import() in a handlerOn the user actionActionExtra latency on click
Prefetch on hoverBefore the clickIntentWasted bytes if unused
next/dynamic with ssr: falseClient only, after hydrationComponentNo server HTML for the widget
Bundle-level split (vendor chunk)With the parent, cached separatelyInfrastructureNot a substitute for route splits

Practical Edge Cases & Deep Dives

1. Route-level splitting with a router

tsx
import { lazy, Suspense } from "react"; import { Routes, Route } from "react-router-dom"; const Home = lazy(() => import("./routes/Home")); const Settings = lazy(() => import("./routes/Settings")); const Reports = lazy(() => import("./routes/Reports")); export function App() { return ( <Suspense fallback={<TopBarLoading />}> <Routes> <Route path="/" element={<Home />} /> <Route path="/settings" element={<Settings />} /> <Route path="/reports" element={<Reports />} /> </Routes> </Suspense> ); }

The fallback sits outside the routed subtree so navigation does not unmount the shell. Placing <Suspense> inside each route gives a more local spinner but remounts the layout on every transition, which loses scroll position and focus.

2. Preloading on intent instead of on render

tsx
const loadEditor = () => import("./Editor"); const Editor = lazy(loadEditor); function EditButton({ onClick }: { onClick: () => void }) { return ( <button onClick={onClick} onMouseEnter={() => { void loadEditor(); }} onFocus={() => { void loadEditor(); }} > Edit </button> ); }

The browser caches the module, so the import() fired on hover makes the subsequent lazy render resolve from cache and skip the fallback entirely. Calling the loader unconditionally at module scope would defeat the split; calling it on intent costs one request for users who actually intend to use the feature.

3. Recovering from a stale chunk after deployment

tsx
class ChunkBoundary extends React.Component< { children: React.ReactNode }, { failed: boolean } > { state = { failed: false }; static getDerivedStateFromError(error: unknown) { const message = error instanceof Error ? error.message : String(error); const isChunkError = /Loading chunk [\d]+ failed|Failed to fetch dynamically imported module/.test(message); return isChunkError ? { failed: true } : { failed: false }; } componentDidCatch(error: unknown) { console.error("chunk load failed", error); } render() { if (this.state.failed) { return ( <div role="alert"> A new version is available. <button onClick={() => window.location.reload()}>Reload</button> </div> ); } return this.props.children; } }

The hash in a chunk filename changes on every build, and a browser tab opened before the deploy keeps referencing the old one. One automatic reload after a chunk error is enough for most apps; a loop guard in sessionStorage prevents a reload storm when the CDN itself is the problem.

4. Lazy components inside a transition

tsx
function Tabs() { const [tab, setTab] = useState<"a" | "b">("a"); const [isPending, startTransition] = useTransition(); function selectTab(name: "a" | "b") { // Inside a transition the old tab stays on screen while the new chunk loads. startTransition(() => setTab(name)); } return ( <div> <button onClick={() => selectTab("a")}>A</button> <button onClick={() => selectTab("b")}>B</button> <div style={{ opacity: isPending ? 0.7 : 1 }}> {tab === "a" ? <TabA /> : <TabB />} </div> </div> ); }

Transitioning the tab state means Suspense does not show its fallback; React keeps the previous tab visible until the chunk resolves. This is the difference between a tab that flashes a skeleton and one that feels instant, and it costs a single startTransition.

5. Splitting a heavy library out of the main bundle

tsx
const MarkdownEditor = lazy(() => Promise.all([ import("@uiw/react-md-editor"), import("remark-gfm"), ]).then(([editor, gfm]) => ({ default: () => <editor.default remarkPlugins={[gfm.default]} />, })) );

Two import() calls resolved together keep the editor and its plugins in the same request batch, so the user does not see a second spinner for the plugin. The library itself is what makes this worth doing: a markdown editor with a syntax highlighter and a plugin chain routinely accounts for more bytes than the rest of the application.

6. When the lazy component never resolves

tsx
function SafeLazy<T extends React.ComponentType<any>>(load: () => Promise<{ default: T }>) { const Component = lazy(() => load().catch((error) => { // Surface a retry-able failure rather than an indefinite Suspense fallback. console.error("lazy load failed", error); throw error; }) ); return function Wrapped(props: React.ComponentProps<T>) { return ( <Suspense fallback={<p>Loading…</p>}> <Component {...props} /> </Suspense> ); }; }

A rejected lazy promise propagates to the nearest error boundary and, without one, unmounts the whole tree. The wrapper makes the failure visible and recoverable instead of leaving the user on a permanent skeleton.

Common Compilation/Runtime Mistakes

SymptomCauseFix
"A component suspended while responding to synchronous input"Suspense boundary below the mounted rootAdd a boundary or wrap the update in a transition
Blank screen after deployStale chunk 404Error boundary with reload
lazy renders undefinedModule has no default exportMap the named export
Fallback flashes on every navigationLazy component rendered for a fraction of a secondPrefetch or transition
Network waterfall of 20 chunksSplitting every componentSplit at routes and heavy widgets
Cannot find module in a testDynamic import not mockedMock the loader or use a stub
Element type is invalidLazy used without Suspense in React 17 or olderWrap it
Hydration mismatch with ssr: falseServer rendered the componentGuard with a mounted check
Chunk served with the wrong MIME typeBase path misconfiguredSet the asset prefix in the bundler
Duplicate downloads of the same moduleDifferent import specifiersImport from one path

Code splitting is a trade between bytes upfront and latency later, and the trade only works when the split points match the user's path through the app. React.lazy gives the mechanism; the boundary placement, the prefetch on intent, and the error boundary for stale chunks are what make it feel like nothing was deferred at all.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.