const Chart = lazy(() => import('./Chart.jsx'));
function Dashboard() {
return (
<Suspense fallback={<Spinner />}>
<Chart />
</Suspense>
);
}
Wrap a dynamic import() in lazy, and render the result inside a <Suspense> boundary.
lazy takes a function that returns a dynamic import() promise and gives you a component. The module is only downloaded the first time that component renders. So bundlers put it in a separate file, called a chunk, and the initial bundle gets smaller.
While the code is loading, the lazy component suspends. That means it tells React it cannot render yet. The nearest <Suspense> boundary above it shows its fallback, for example a spinner. Once the code loads, React renders the real component. The imported module must have a default export that is a component.
Good places to split are routes, modals and heavy widgets like charts or editors. Declare lazy components at the top level of a module, never inside another component. Also wrap them in an error boundary, because the network request for the chunk can fail.
lazy(() => import('./X'))loads the code the first time the component renders.- The code goes into a separate chunk, so the initial bundle is smaller.
- The nearest
Suspenseshows its fallback while the code loads. - Split by route, or by heavy UI that is rarely used.
- Declare lazy components at module top level and add an error boundary.