How does Suspense work with lazy components?
Suspense and lazy components work hand-in-hand to make code splitting simple and seamless in React.
- React provides
React.lazy()
to dynamically import a component only when it is needed. React.lazy()
returns a special version of the component that can tell React it is not ready yet.- When React hits a lazy component that isn’t ready, it looks for the nearest
<Suspense>
boundary and shows the fallback instead of crashing.
Here's the flow:
- You use
React.lazy(() => import('./MyComponent'))
to dynamically load a component. - The component isn’t immediately available.
- React suspends rendering at that point.
- The
<Suspense fallback={...}>
UI is displayed. - Once the component is loaded, React resumes rendering with the loaded component.
Example:
import { lazy, Suspense } from 'react'; const MyLazyComponent = lazy(() => import('./MyLazyComponent')); function App() { return ( <Suspense fallback={<h1>Loading component...</h1>}> <MyLazyComponent /> </Suspense> ); }
Key Takeaways:
lazy
is for dynamic imports.Suspense
is for handling the waiting.- Together, they improve performance and user experience by loading only what's needed when it's needed.