React.lazy() is used to load a component only when it is needed instead of loading all components at the beginning.
Normally, React loads all imported components when the application starts.
With lazy loading, React loads a component only when we need it.
Example:
import React, { lazy, Suspense } from 'react';
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
function App() {
return (
Loading...}>
);
}
export default App;
Advantages of Lazy Loading:
- Faster Initial Loading: The website loads faster because it doesn't load all components at once.
- Improved Performance: Reduces the amount of JavaScript loaded initially.
- Code Splitting: Divides large JavaScript files into smaller files.
- Saves Bandwidth: Downloads components only when required.
- Better User Experience: Users can access the main page faster.
- Useful for Large Applications: Especially useful for websites with multiple pages.
Disadvantages of Lazy Loading:
- Loading Delay: Components may take extra time to appear when opened.
- Internet Dependency: Slow internet can make lazy-loaded components take longer to load.
- More Complexity: Requires additional implementation using React.lazy() and Suspense.
- Additional Network Requests: Components may require separate JavaScript file downloads.
- Error Handling: If a component fails to load, an Error Boundary is needed to handle the error.
Top comments (0)