React’s lazy loading and the Suspense component are powerful tools for optimizing application performance. They enable loading components or modules only when needed, improving initial load times and reducing bundle size.
What is React Lazy Loading?
Lazy loading is a technique where components are loaded dynamically, i.e., only when they are required. React provides the React.lazy()
function to implement this feature.
What is Suspense?
The Suspense
component is used to handle the loading state of components that are being lazy-loaded. It allows you to define a fallback UI (like a spinner) that is displayed while the component is loading.
Steps to Implement Lazy Loading with Suspense
-
Dynamic Import with
React.lazy()
UseReact.lazy()
to dynamically load a component. -
Wrap with
Suspense
Wrap lazy-loaded components withSuspense
to show a fallback while the component loads.