import { RefObject, useEffect, useMemo, useState } from "react"; export function useIntersection( ref: RefObject, options?: { root?: Element | Document | null | undefined; rootMargin?: string | undefined; threshold?: number | number[] | undefined; }, initialState?: { isIntersecting?: boolean; }, ) { const defaultIsIntersecting = initialState && typeof initialState.isIntersecting !== "undefined" ? initialState.isIntersecting : false; const [isIntersecting, setIsIntersecting] = useState(defaultIsIntersecting); const observer = useMemo( () => new IntersectionObserver( ([entry]) => setIsIntersecting(entry.isIntersecting), { root: undefined, rootMargin: "0px", threshold: 1.0, ...options, }, ), [options], ); useEffect(() => { if (ref && ref.current) { observer.observe(ref.current); } return () => { observer.disconnect(); }; }, [observer, ref]); return isIntersecting; }