DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is Lazy Loading in React?

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:

  1. Faster Initial Loading: The website loads faster because it doesn't load all components at once.
  2. Improved Performance: Reduces the amount of JavaScript loaded initially.
  3. Code Splitting: Divides large JavaScript files into smaller files.
  4. Saves Bandwidth: Downloads components only when required.
  5. Better User Experience: Users can access the main page faster.
  6. Useful for Large Applications: Especially useful for websites with multiple pages.

Disadvantages of Lazy Loading:

  1. Loading Delay: Components may take extra time to appear when opened.
  2. Internet Dependency: Slow internet can make lazy-loaded components take longer to load.
  3. More Complexity: Requires additional implementation using React.lazy() and Suspense.
  4. Additional Network Requests: Components may require separate JavaScript file downloads.
  5. Error Handling: If a component fails to load, an Error Boundary is needed to handle the error.

Top comments (0)