Skip to main content

lazy and code splitting

lazy lets React defer loading a component's code until that component is rendered for the first time.

import { lazy, Suspense } from 'react';

const SettingsPage = lazy(() => import('./SettingsPage.js'));

export default function App() {
return (
<Suspense fallback={<SettingsSkeleton />}>
<SettingsPage />
</Suspense>
);
}
lazy, dynamic import, and Suspense have different jobs
BUNDLER / MODULEdynamic import()

Creates an async module loading boundary.

REACT COMPONENTlazy

Turns that async module into a component React can render.

REVEAL UXSuspense

Defines what users see while the code is not ready.

What happens on first render?​

1Render lazy component
2Run loader
3Module pending → suspend
4Nearest fallback shows
5Module resolves
6Retry + commit component

React caches the loader Promise and resolved module value for that lazy component definition, so the same loader is not expected to run on every later render.

The module needs a default component export​

// ReportsPage.js
export default function ReportsPage() {
return <h1>Reports</h1>;
}
const ReportsPage = lazy(() => import('./ReportsPage.js'));

If a module only has named exports, use a deliberate adapter rather than spreading special Promise mapping throughout the app.

Declare lazy components at module scope​

Good:

const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));

export default function Editor() {
return <MarkdownPreview />;
}

Bad:

export default function Editor() {
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
return <MarkdownPreview />;
}
Component identity must stay stable
Module-scope lazy definition

Same component type across renders → normal state preservation rules apply.

lazy created during render

New component type may be created → state can reset unexpectedly.

Lazy loading is not conditional rendering​

{showChart ? <Chart /> : null}

Conditional rendering decides whether the component exists in the current UI. If Chart is statically imported, its code may already be in the bundle.

import Chart from './Chart.js';

With lazy, the code itself can be deferred.

Choose product boundaries, not tiny components​

Strong candidates include routes, large editors, analytics views, admin-only features, heavy visualization tools, rare modals, and optional integrations.

Is this a useful lazy boundary?
Large feature, not needed immediatelyStrong candidate
Route many users may never visitStrong candidate
Tiny component always needed above the foldUsually keep eager
Split creates extra sequential discoveryReconsider or preload

Code splitting can create waterfalls​

Bad splitting can defer too much work sequentially.

A code-split waterfall still costs time
Load route JS
Load chart JS
Load editor JS
Interactive feature

Good production architecture asks what can load in parallel, what should be prefetched, what belongs on the critical path, and whether the extra chunk boundary is worth its scheduling/network overhead.

Route-level and feature-level splitting​

const HomePage = lazy(() => import('./pages/HomePage.js'));
const BillingPage = lazy(() => import('./pages/BillingPage.js'));
const AdminPage = lazy(() => import('./pages/AdminPage.js'));
const AdvancedReportBuilder = lazy(
() => import('./reports/AdvancedReportBuilder.js')
);

Routes are often strong boundaries because users may never visit every route. Feature boundaries work when large code is only needed after a specific interaction.

Suspense fallback design​

Avoid a giant page spinner for a small lazy panel.

<DashboardShell>
<Suspense fallback={<ChartSkeleton />}>
<RevenueChart />
</Suspense>
</DashboardShell>
Keep useful surrounding UI outside the lazy region
Dashboard shell stays visible
Chart skeleton
Revenue chart

Failed lazy imports are errors​

If the import Promise rejects, the nearest Error Boundary should own recovery.

Chunk failures can happen because of deployment mismatches, stale HTML, CDN issues, or offline conditions. A robust app may need local recovery UI, retry, a controlled refresh path, and monitoring.

Prefetching complements lazy loading​

lazy answers what can load later. Prefetch/preload answers when to begin fetching likely future code before render requires it.

Split less now, preload selectively later
lazy
Remove code from the initial requirement.
preload / prefetch
Start likely future code before the interaction needs it.

React DOM exposes APIs such as preloadModule and preinitModule; routers and frameworks may provide their own prefetch mechanisms. Preloading everything defeats the bandwidth benefit of splitting.

Bundler responsibility​

React expresses runtime loading, but the bundler creates the actual chunk graph. Production debugging often requires inspecting generated bundles and browser network activity, not only React source code.

Inspect:

  • chunk sizes;
  • duplicate dependencies;
  • request waterfalls;
  • cache behavior;
  • chunk-load failures;
  • code loaded before it is needed;
  • fallback replacement caused by boundary placement.

A lazy route can prepare inside a Transition while the current route remains visible.

Suspense-aware navigation can avoid destructive route replacement
Current route visible
Next route chunk prepares
Next route ready → commit

If old content stays visible, users still need feedback that their navigation was accepted.

Production decision framework​

Before adding lazy, ask:

  1. Is the feature large enough to split?
  2. Is it needed on the first user journey?
  3. How likely is the user to open it?
  4. Can likely navigation preload it?
  5. Where should Suspense live?
  6. What happens if the chunk fails?
  7. Does the split introduce a waterfall?

Exercise​

Take Home, Reports, Billing, and Admin routes. Measure an eager build, lazy-load the less common routes, add Suspense and pending navigation UI, then inspect the resulting Network waterfall and bundle graph.

Interview questions​

Beginner: What does lazy do?

Intermediate: Why should a lazy component normally be declared outside component functions?

Senior: How do you choose code-splitting boundaries without creating network waterfalls or damaging perceived navigation performance?

Summary​

Code-splitting mental model
Choose a meaningful product boundary
lazy + dynamic import
Suspense + pending/error UX
Parallel loading, caching, selective prefetch

References​

Next​

Next, design loading and navigation states across multiple Suspense boundaries.