DEV Community

Keertivaas S
Keertivaas S

Posted on

Lazy Loading :)

Sometimes a user might not click and view a part of the code. In that case, it doesn't make sense to load the component before we render the main screen. This is where Lazy Loading comes in.

Code example :

import React, { lazy, Suspense, useState } from 'react';

// Import component A directly (eager loading)
import A from './A';

// Lazy load component B
const B = React.lazy(() => import('./B'));

const App = () => {
  const [showComponentB, setShowComponentB] = useState(false);

  const handleClick = () => {
    setShowComponentB(true);
  };

  return (
    <div>
      <A />
      <button onClick={handleClick}>Click to view Component B</button>
      {showComponentB && (
        <Suspense fallback={<div>Loading...</div>}>
          <B />
        </Suspense>
      )}
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

Here, the code imports A directly, assuming it's needed on the landing page (eager loading). B is lazy loaded using React.lazy and Suspense.

The render doesn't have to wait for B, before rendering A :)

Top comments (1)

Collapse
 
shaogat_alam_1e055e90254d profile image
Shaogat Alam

Interesting topic! Everything is explained articulately and clearly. For your project, consider checking out this free npm package: select-paginated.