pstream is dead; long live pstream taciturnaxolotl.github.io/pstream-ng/
at main 43 lines 1.1 kB view raw
1import { useEffect, useRef, useState } from "react"; 2 3interface IntersectionObserverOptions { 4 root?: Element | null; 5 rootMargin?: string; 6 threshold?: number | number[]; 7} 8 9export function useIntersectionObserver( 10 options: IntersectionObserverOptions = {}, 11) { 12 const [isIntersecting, setIsIntersecting] = useState(false); 13 const [hasIntersected, setHasIntersected] = useState(false); 14 const targetRef = useRef<Element | null>(null); 15 16 useEffect(() => { 17 const observer = new IntersectionObserver( 18 ([entry]) => { 19 setIsIntersecting(entry.isIntersecting); 20 if (entry.isIntersecting) { 21 setHasIntersected(true); 22 } 23 }, 24 { 25 ...options, 26 rootMargin: options.rootMargin || "400px 0px", 27 }, 28 ); 29 30 const currentTarget = targetRef.current; 31 if (currentTarget) { 32 observer.observe(currentTarget); 33 } 34 35 return () => { 36 if (currentTarget) { 37 observer.unobserve(currentTarget); 38 } 39 }; 40 }, [options]); 41 42 return { targetRef, isIntersecting, hasIntersected }; 43}