Files
WrenchBoardMainSite2025/app/lib/LazyImage.js
T
CHIEFSOFT\ameye 1bd5892cc4 fix
2024-07-29 13:33:26 -04:00

53 lines
1.4 KiB
JavaScript

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 (
<img
ref={imgRef}
src={isVisible ? src : ''}
alt={alt}
loading="lazy"
className={isVisible ? 'visible' : 'hidden'} // You can apply CSS classes for animations
/>
);
}
export default LazyImage;