ESC

Type to search the knowledge base.

Code Splitting with React.lazy

React.lazy and Suspense split bundles: dynamic import, loading fallbacks, error boundaries, and route-level splits.

intermediate3 min read
  • react
  • code-splitting

Shipping one giant JS bundle makes first load pay for screens the user never opens. React.lazy plus dynamic import() loads a component’s code when it is first rendered, while Suspense shows a fallback until the chunk arrives.

Docs: Code-Splitting, Suspense.

Basic pattern

import { lazy, Suspense } from 'react';

const MarkdownEditor = lazy(() => import('./MarkdownEditor'));

function NotePage() {
  return (
    <Suspense fallback={<p>Loading editor…</p>}>
      <MarkdownEditor />
    </Suspense>
  );
}

lazy expects a function that returns a promise of a module with a default export component.

Route-level splits

The highest ROI is splitting by route:

const Settings = lazy(() => import('./pages/Settings'));
const Billing = lazy(() => import('./pages/Billing'));

<Route path="/settings" element={
  <Suspense fallback={<PageSkeleton />}>
    <Settings />
  </Suspense>
} />

Frameworks (Next.js, Remix) often do this automatically with file-based routing — still understand the model for SPA sections and heavy widgets (charts, editors, admin tools).

Error handling

A failed chunk load throws — wrap with an error boundary:

<ErrorBoundary fallback={<p>Could not load. Refresh.</p>}>
  <Suspense fallback={<Spinner />}>
    <AdminPanel />
  </Suspense>
</ErrorBoundary>

Named exports

// lazy needs default — re-export if needed
export { Chart as default } from './Chart';

Or lazy(() => import('./Chart').then((m) => ({ default: m.Chart }))).

What not to split

Tiny components, above-the-fold critical UI, and anything on the critical path for LCP. Measure with coverage and Network panels. Prefetch on hover for likely next routes when using client routers.

Interview out-loud

“React.lazy uses dynamic import to load a component on first render, and Suspense shows a fallback while the chunk loads. I split heavy routes and widgets, wrap with error boundaries for failed loads, and avoid splitting critical above-the-fold UI.”

Further reading

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides