Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I optimize lazy loading images for better performance in a React app?
Asked on Dec 31, 2025
Answer
Optimizing lazy loading of images in a React app can significantly enhance performance by deferring the loading of off-screen images until they are needed. This approach reduces initial load time and improves user experience, especially on pages with many images.
<!-- BEGIN COPY / PASTE -->
import React, { useState, useEffect } from 'react';
const LazyImage = ({ src, alt }) => {
const [isVisible, setIsVisible] = useState(false);
const imgRef = React.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);
}
};
}, [imgRef]);
return (
<img
ref={imgRef}
src={isVisible ? src : ''}
alt={alt}
loading="lazy"
style={{ minHeight: '200px', minWidth: '200px' }}
/>
);
};
export default LazyImage;
<!-- END COPY / PASTE -->Additional Comment:
- Use the `IntersectionObserver` API to detect when an image enters the viewport.
- Set the `loading="lazy"` attribute as a fallback for browsers that support native lazy loading.
- Ensure images have a defined size to prevent layout shifts during loading.
- Consider using a placeholder or a low-resolution image while the main image loads.
- Test across different devices and network conditions to ensure consistent performance.
Recommended Links:
