Sub topic 1
React Suspense and Lazy Loading: Split Code, Show Fallbacks, Handle Failures
Prerequisites
Assume you know React function components, props, basic hooks, ES modules, promises, and how a bundler such as Vite or webpack builds an application.
Why split code: bundles and load cost
A bundle is JavaScript packaged for delivery to the browser. Without code splitting, the browser may download code for every page before showing the first screen. This increases download time, parsing time, and startup work.
Code splitting divides the application into smaller files called chunks. The initial page downloads only the code it needs. Other chunks load later when the user needs them. Splitting helps most when an application has large, rarely visited areas such as reports, editors, or administration screens.
Dynamic import() and chunks
A dynamic import uses import() as a function. It returns a promise for a module. A bundler usually turns that import into a separate chunk.
const chartModule = import('./Chart');
// chartModule resolves after the Chart chunk has loadedThe path should usually be statically recognizable to the bundler. A fully arbitrary path can prevent predictable chunk generation or include more files than intended.
Loading components on demand with React.lazy
React.lazy converts a promise for a module into a React component. React starts the import when the component first renders. The module must provide a default export.
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
export default function Dashboard() {
return (
<section>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</section>
);
}Suspense supplies temporary UI while the lazy component is waiting. The fallback should describe the missing content and fit its space, so the page does not shift unnecessarily.
Exercise
What does the promise returned by import('./Chart') represent?
Show answer
It represents the future module value, resolved after the bundler's chart chunk has loaded.