React › Code Splitting & Lazy Loading
How do React.lazy and Suspense work together to load a component only when it is needed?
IntermediateAnswer
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.