Code Splitting with React.lazy
React.lazy and Suspense split bundles: dynamic import, loading fallbacks, error boundaries, and route-level splits.
- 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.”
Related on this site
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
- useCopyToClipboard HookCopy text with navigator.clipboard, fallback execCommand, transient copied state, and permissions that fail in insecure contexts.
- useDebouncedValue HookDebounce a changing value in React without firing effects on every keystroke. Cleanup, leading vs trailing, and the stale timer that updates unmounted state.
- useEventListener HookAttach a window, document, or element listener with a stable handler ref so you do not rebind on every render. Capture option and target changes.
- useFetch With AbortControllerFetch in an effect with a signal, ignore aborted errors, and prevent the slow response from winning a race after the url changes.
- useIdle HookDetect idle users: reset a timer on input events, fire idle after timeout, and decide whether mount starts the timer immediately.