React Reference ยท Top-Level React APIs
React lazy() function
Reference for React lazy: load a component's code on first render, wrap it in Suspense, handle load errors and keep the import at module level.
lazy lets you postpone loading a component's code until it is rendered for the first time. You give it a function that returns a promise, normally a dynamic import(). React calls that function the first time the lazy component is about to render and suspends until the promise settles, so a Suspense boundary above it shows a fallback in the meantime.
This is how you split a big app into chunks: the heavy chart, editor or admin page is downloaded only when somebody needs it.
import { lazy } from 'react'; const Chart = lazy(() => import('./Chart.js'));
Try it
In the first example the loader is called once, no matter how often you hide and show the report: React caches the settled result.
Syntax
function lazy<T extends ComponentType<any>>( load: () => Promise<{ default: T }> ): LazyExoticComponent<T>;
| Name | Description |
|---|---|
load |
A function with no arguments that returns a promise (or a thenable). It must resolve to an object with a default property holding a component. |
Returns: a component you render like any other. Its props are passed to the loaded component.
Edge cases: if the promise rejects, the error is thrown during render and must be caught by an error boundary. If the module has no default export, React throws an error that mentions it. load is called at most once per lazy component.
Usage notes
- Declare at module level. Calling
lazyinside a component creates a new component type on every render, which resets state and reloads the code. - Always render inside
Suspense. Without a boundary above, React throws. One boundary can cover several lazy components. - Named exports need an adapter:
lazy(() => import('./ui.js').then((m) => ({ default: m.Chart }))). - Split at routes first. The biggest wins come from loading a whole screen on demand, not tiny widgets. See code splitting.
- Avoid waterfalls. A lazy component that itself renders another lazy component loads them one after the other. Preload with
import()on hover or idle if the delay matters. - Transitions keep the old UI. If the lazy component appears because of an update wrapped in a transition, React keeps showing the previous screen instead of replacing it with the fallback.
- Not for server-only code. In frameworks with Server Components, prefer the framework's own dynamic-import helper for route splitting.