import React, { useEffect, useRef, useState } from 'react'; /** * Renders an image lazily using the Intersection Observer API. * The image is initially hidden and becomes visible once it enters the viewport. * This approach improves performance by only loading images that are actually visible to the user. * * @returns {JSX.Element} - The lazy image component. */ function LazyImage({ src, alt }) { const imgRef = useRef(); const [isVisible, setIsVisible] = useState(false); useEffect(() => { const observer = new IntersectionObserver( (entries) => { const [entry] = entries; if (entry.isIntersecting) { setIsVisible(true); observer.unobserve(imgRef.current); // Stop observing once the image is in the viewport } }, { root: null, // Viewport rootMargin: '0px', // No margin threshold: 0.1, // Percentage of the image that needs to be visible } ); if (imgRef.current) { observer.observe(imgRef.current); } return () => { if (imgRef.current) { observer.unobserve(imgRef.current); } }; }, []); return ( {alt} ); } export default LazyImage;