I want to improve the loading time of my React app. Can anyone explain how to implement lazy loading for components and routes?
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.