How do I implement lazy loading in a React application?Dec 16, 2024

I want to improve the loading time of my React app. Can anyone explain how to implement lazy loading for components and routes?

React
Answers (1)
Harun KaranjaDec 17, 2024

To implement lazy loading in React, use the React.lazy() function for components and Suspense for fallback handling. For example:

const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
 return (
   <Suspense fallback={<div>Loading...</div>}>
     <LazyComponent />
   </Suspense>
 );
}

For routing, use React.lazy() with React Router:

const HomePage = React.lazy(() => import('./HomePage'));
<Route path="/" component={HomePage} />

This will load components only when they are needed.

Leave an answer