Back to results for “Error Boundaries”
React › Code Splitting & Lazy Loading

How do React.lazy and Suspense work together to load a component only when it is needed?

Intermediate

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.

Common 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?