Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
What are the best practices for implementing lazy loading of images in a React app?
Asked on Dec 23, 2025
Answer
Lazy loading images in a React app is a performance optimization technique that delays the loading of images until they are needed, improving initial page load times. This can be implemented using the Intersection Observer API or third-party libraries like `react-lazyload`.
<!-- BEGIN COPY / PASTE -->
import React, { useEffect, useRef } from 'react';
const LazyImage = ({ src, alt }) => {
const imgRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
imgRef.current.src = src;
observer.disconnect();
}
},
{ threshold: 0.1 }
);
if (imgRef.current) {
observer.observe(imgRef.current);
}
return () => {
if (imgRef.current) {
observer.unobserve(imgRef.current);
}
};
}, [src]);
return <img ref={imgRef} alt={alt} />;
};
export default LazyImage;
<!-- END COPY / PASTE -->Additional Comment:
- Ensure images have width and height attributes to prevent layout shifts.
- Consider using a placeholder or blurred image effect while images load.
- Test lazy loading performance across different devices and network conditions.
- For a simpler implementation, explore libraries like `react-lazyload` or `react-lazy-load-image-component`.
- Always verify browser support for Intersection Observer API or provide a fallback.
Recommended Links:
