How do React.lazy and Suspense work together to load a component only when it is needed?
Short answer
React.lazy takes a function that dynamically imports a component, and returns a special component that only actually loads that code the first time it is rendered.
Advertisement
AModel answer
React.lazy takes a function that dynamically imports a component, and returns a special component that only actually loads that code the first time it is rendered. Suspense wraps around it and shows a fallback, like a loading spinner, while the code is still being downloaded in the background.
const Settings = React.lazy(() => import('./Settings'));
function App() {
return (
<Suspense fallback={<div>Loading settings</div>}>
<Settings />
</Suspense>
);
}Real-world example
A dashboard shows a small loading spinner for less than a second while the rarely used reports section loads in the background the first time a user clicks on it.
Likely follow-ups
- What happens if the lazy loaded component fails to download because of a network problem?
- Can you use React.lazy for something other than a whole page component?
Related topics