Intersection Observer Hook for Lazy Loading and Animations
A lightweight, reusable React hook that triggers callbacks when elements enter or leave the viewport—ideal for lazy-loading images or starting animations.
Use useIntersectionObserver by calling the returned setTarget ref callback on a DOM element (e.g., <img ref={setTarget} />). The hook returns [setTarget, isIntersecting, entry], letting you conditionally load images (src → data-src) or trigger CSS animations when isIntersecting becomes true. It auto-cleans up the observer on unmount and supports custom threshold/rootMargin. ⚠️ Avoid re-creating the hook’s options object on every render—pass stable values (e.g., memoize with useMemo if needed). Example: const [ref, inView] = useIntersectionObserver({ threshold: 0.1 }); <div ref={ref}>{inView ? <AnimatedContent /> : <Placeholder />}</div>.