How to lazy load components in React?

Lazy loading in React allows components to be loaded only when they are needed, speeding up the initial page load time. Here is how you can lazy load components in React:

  1. Use React.lazy() and Suspense: React.lazy() allows you to dynamically import a component only when it needs to be rendered. The Suspense component can be used to show a loading spinner while the component is being loaded.
import React, { Suspense } from 'react'; const LazyComponent = React.lazy(() => import('./LazyComponent')); const App = () => { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); } export default App;
  1. Code splitting: In order to lazy load components, you can also use code splitting using dynamic imports.
const LazyComponent = lazy(() => import('./LazyComponent'));
  1. React Loadable: You can also use a library like React Loadable to lazy load components.
import Loadable from 'react-loadable'; const LoadableComponent = Loadable({ loader: () => import('./LazyComponent'), loading() { return <div>Loading...</div>; } }); const App = () => { return ( <LoadableComponent /> ); }

By lazy loading components in React, you can optimize the performance of your web application by only loading the necessary components when they are needed, rather than all at once.