typescriptintermediate

useIntersectionObserver Hook

Track element visibility with the Intersection Observer API for lazy loading and scroll animations.

typescript
import { useEffect, useRef, useState } from 'react';

export function useIntersectionObserver(
  options: IntersectionObserverInit = {}
) {
  const ref = useRef<HTMLElement>(null);
  const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;

    const observer = new IntersectionObserver(
      ([e]) => setEntry(e),
      { threshold: 0.1, ...options }
    );
    observer.observe(node);
    return () => observer.disconnect();
  }, [options.threshold, options.root, options.rootMargin]);

  return { ref, entry, isVisible: entry?.isIntersecting ?? false };
}

Use Cases

  • Lazy loading images
  • Infinite scroll triggers
  • Scroll-based animations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.