Skip to content

Instantly share code, notes, and snippets.

@thearyanahmed
Created January 1, 2025 10:09
Show Gist options
  • Save thearyanahmed/200d2665a79d5e4e66121845fb774f94 to your computer and use it in GitHub Desktop.
Save thearyanahmed/200d2665a79d5e4e66121845fb774f94 to your computer and use it in GitHub Desktop.
Lazy image thingy
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