Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I implement lazy loading for images in a React application?
Asked on Feb 28, 2026
Answer
Lazy loading images in a React application can significantly enhance performance by deferring the loading of images until they enter the viewport. This can be achieved using the `IntersectionObserver` API or by leveraging libraries like `react-lazyload` or `react-intersection-observer`.
<!-- BEGIN COPY / PASTE -->
import React, { useRef, useEffect, useState } from 'react';
const LazyImage = ({ src, alt }) => {
const [isVisible, setIsVisible] = useState(false);
const imgRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.disconnect();
}
},
{ threshold: 0.1 }
);
if (imgRef.current) {
observer.observe(imgRef.current);
}
return () => {
if (imgRef.current) {
observer.unobserve(imgRef.current);
}
};
}, []);
return (
<img
ref={imgRef}
src={isVisible ? src : ''}
alt={alt}
style={{ minHeight: '200px', backgroundColor: '#f0f0f0' }}
/>
);
};
export default LazyImage;
<!-- END COPY / PASTE -->Additional Comment:
- Use the `IntersectionObserver` API for efficient lazy loading without external dependencies.
- Consider using libraries like `react-lazyload` for more features and ease of use.
- Ensure images have a placeholder or minimum height to avoid layout shifts.
- Test lazy loading on different devices to ensure consistent behavior.
Recommended Links:
