Detect when an element enters or leaves the viewport. Useful for lazy loading and scroll animations.
import { useState, useEffect, RefObject } from 'react';
export function useIntersectionObserver(
ref: RefObject<Element | null>,
options: IntersectionObserverInit = {}
): boolean {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const el = ref?.current;
if (!el) return;
const observer = new IntersectionObserver(([entry]) => {
setIntersecting(entry.isIntersecting);
}, options);
observer.observe(el);
return () => observer.disconnect();
}, [ref, options.threshold, options.rootMargin, options.root]);
return isIntersecting;
}Paste into your project. Requires a ref to the element you want to observe.
Pass a ref and optional IntersectionObserver options (rootMargin, threshold). Returns true when the element is in view.
const ref = useRef(null); const isVisible = useIntersectionObserver(ref, { threshold: 0.1 });