Lazy Loading :)

Keertivaas S - Jul 6 - - Dev Community

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 :)

. . . . . . . . .
Terabox Video Player