Imagine you are browsing a website with lots of images. Instead of all the images loading at once , which can make the page feel slow, lazy loading means that the images only load as you scroll down the page.
- In React , we can implement lazy loading for images using built-in lazy and Suspense components.
- Import Necessary Components:
import React , {lazy , Suspense } from 'react';
- Create a Lazy-Loaded Component:
const LazyImage = lazy(() => import('./MyImage'));
- Wrap with Suspense :
<Suspense fallback = {<div>Loading...</div>}>
<LazyImage src= "path/to/image.jpg" alt="Image"/>
</Suspense>
Complete Example :
import React , {lazy , Suspense } from 'react';
const LazyImage = lazy(() => import('./MyImage'));
function My(){
return (
<div>
<Suspense fallback = {<div>Loading...</div>}>
<LazyImage src= "path/to/image.jpg" alt="Image"/>
</Suspense>
</div>
);
}
- The lazy function dynamically imports the MyImage , ensuring it’s only loaded when needed.
- The Suspense component provides a fallback UI while the image is loading.
- Once the image is loaded, the LazyImage component will render in place of the fallback.