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 }…


This content originally appeared on DEV Community and was authored by Keertivaas S

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;

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


This content originally appeared on DEV Community and was authored by Keertivaas S


Print Share Comment Cite Upload Translate Updates
APA

Keertivaas S | Sciencx (2024-07-06T13:36:54+00:00) Lazy Loading :). Retrieved from https://www.scien.cx/2024/07/06/lazy-loading/

MLA
" » Lazy Loading :)." Keertivaas S | Sciencx - Saturday July 6, 2024, https://www.scien.cx/2024/07/06/lazy-loading/
HARVARD
Keertivaas S | Sciencx Saturday July 6, 2024 » Lazy Loading :)., viewed ,<https://www.scien.cx/2024/07/06/lazy-loading/>
VANCOUVER
Keertivaas S | Sciencx - » Lazy Loading :). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/06/lazy-loading/
CHICAGO
" » Lazy Loading :)." Keertivaas S | Sciencx - Accessed . https://www.scien.cx/2024/07/06/lazy-loading/
IEEE
" » Lazy Loading :)." Keertivaas S | Sciencx [Online]. Available: https://www.scien.cx/2024/07/06/lazy-loading/. [Accessed: ]
rf:citation
» Lazy Loading :) | Keertivaas S | Sciencx | https://www.scien.cx/2024/07/06/lazy-loading/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.