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
Keertivaas S | Sciencx (2024-07-06T13:36:54+00:00) Lazy Loading :). Retrieved from 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.