import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; const noopSubscribe = () => () => {}; type UseInViewOptions = { threshold?: number; rootMargin?: string; // Skip observing and report "in view" right away skip?: boolean; }; // Tells whether an element has come into (or near) the viewport, once. // Without IntersectionObserver the element counts as in view (from the first // render after hydration), so content is never left hidden or unloaded. export default function useInView({ threshold = 0, rootMargin = '0px', skip = false, }: UseInViewOptions = {}) { const ref = useRef(null); // The server cannot know, so prerender and hydration both assume support const unsupported = useSyncExternalStore( noopSubscribe, () => typeof IntersectionObserver === 'undefined', () => false, ); const [intersected, setIntersected] = useState(false); useEffect(() => { const element = ref.current; if (!element || skip || unsupported || intersected) return; const observer = new IntersectionObserver( (entries) => { if (entries.some((entry) => entry.isIntersecting)) { setIntersected(true); observer.disconnect(); } }, { threshold, rootMargin }, ); observer.observe(element); return () => observer.disconnect(); }, [skip, unsupported, intersected, threshold, rootMargin]); return { ref, inView: skip || intersected || unsupported }; }