Lazy Loading
- React
Deferring the loading of a component or resource until it is actually needed, so the initial page loads faster and the rest arrives on demand.
Prerequisites
- React components; performance basics help (see Related Topics)
What you'll understand
- What lazy loading defers and why
- How React loads a component on demand
- What to show while a lazy part is loading
Explanation
Lazy loading means not loading something until it is actually needed. Instead of downloading every screen, image, and component up front, you defer the parts a user may never reach and load them on demand. The payoff is a faster initial load: the browser downloads and runs less code before the first screen appears.
In React, you lazy-load a component with React.lazy, which turns a normal import into one that loads only when the component first renders. Because that load is asynchronous, you wrap the lazy component in a Suspense boundary that shows a fallback (such as a spinner) while the code is arriving. Good candidates are routes the user has not visited yet, heavy components like a rich editor, or anything behind a tab or modal.
Lazy loading is the mechanism that makes code splitting (see Related Topics) useful: splitting produces separate chunks, and lazy loading is how you fetch a chunk only when required. The same principle applies beyond components, for example deferring off-screen images, and it is one of the highest-impact ways to improve perceived performance without changing what the app does.
Examples
React.lazy defers loading a component until it renders; Suspense provides the fallback:
import { lazy, Suspense } from 'react';
const Editor = lazy(() => import('./Editor'));
function Page() {
return (
<Suspense fallback={<Spinner />}>
<Editor />
</Suspense>
);
}Common mistakes
- Forgetting the Suspense boundary, so a lazy component has no fallback.
- Lazy-loading tiny components where the overhead outweighs the benefit.
- Lazy-loading content needed immediately on the first screen, hurting the experience.
- Not handling the case where loading the chunk fails.
Best practices
- Lazy-load routes and heavy components that are not needed on first paint.
- Wrap lazy components in a Suspense boundary with a sensible fallback.
- Combine lazy loading with code splitting for the biggest wins (see Related Topics).
- Handle load failures so a missing chunk does not break the page.
Further reading
- React, lazy — https://react.dev/reference/react/lazy
- React, Suspense — https://react.dev/reference/react/Suspense