Lazy loading of images in a React.js app can significantly improve performance by deferring the loading of non-critical images until they are needed. This can be achieved using the IntersectionObserver
API, which allows you to observe when an element enters the viewport. Here's a step-by-step guide on how to implement lazy loading of images in a React.js app:
Install Dependencies: Ensure you have React installed in your project. If not, you can install it using npm or yarn:
bashnpm install react react-dom
Create a LazyImage Component:
Create a reusable component for lazy-loaded images. This component will use the IntersectionObserver
to determine when the image is in the viewport and load it accordingly.
jsximport React, { useRef, useEffect, useState } from 'react';
const LazyImage = ({ src, alt }) => {
const imageRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.unobserve(entry.target);
}
});
});
if (imageRef.current) {
observer.observe(imageRef.current);
}
return () => {
if (imageRef.current) {
observer.unobserve(imageRef.current);
}
};
}, []);
return (
<img
ref={imageRef}
src={isVisible ? src : ''}
alt={alt}
/>
);
};
export default LazyImage;
Use LazyImage Component:
Now, you can use the LazyImage
component wherever you want to load images lazily in your React app. Pass the src
and alt
attributes to the component.
jsximport React from 'react';
import LazyImage from './LazyImage';
const App = () => {
return (
<div>
{/* Placeholder image until lazy loading kicks in */}
<div style={{ height: '200px' }}>
Placeholder
</div>
<LazyImage
src="your-image-path.jpg"
alt="Your image"
/>
</div>
);
};
export default App;
CSS Styling (Optional): You might want to add some CSS to your images to ensure they maintain the correct aspect ratio while lazy loading. For example:
cssimg {
width: 100%;
height: auto;
}
That's it! You've implemented lazy loading of images in your React.js app using the Intersection Observer API. Now, images will be loaded only when they are about to be displayed in the viewport, improving the performance of your application.