Created
January 1, 2025 10:09
-
-
Save thearyanahmed/200d2665a79d5e4e66121845fb774f94 to your computer and use it in GitHub Desktop.
Lazy image thingy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useRef } from "react"; | |
const LazyImage = ({ src, alt, className }) => { | |
const [isVisible, setIsVisible] = useState(false); | |
const imgRef = useRef(null); | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
if (entry.isIntersecting) { | |
setIsVisible(true); | |
observer.disconnect(); // Stop observing after the image is visible | |
} | |
}, | |
{ | |
root: null, // Use the viewport as the root | |
rootMargin: "100px", // Preload images when they are 100px from the viewport | |
threshold: 0.1, // Trigger when 10% of the image is visible | |
} | |
); | |
if (imgRef.current) { | |
observer.observe(imgRef.current); | |
} | |
return () => observer.disconnect(); | |
}, []); | |
return ( | |
<img | |
ref={imgRef} | |
src={isVisible ? src : undefined} // Only load the image when it's visible | |
alt={alt} | |
className={className} | |
/> | |
); | |
}; | |
export default LazyImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment