REACT

useIntersectionObserver Hook

A custom React Hook for detecting element visibility with Intersection Observer API and TypeScript support

ReactHooksIntersectionObserverPerformanceLazyLoad

Code

import { useState, useEffect, RefObject } from 'react';

type IntersectionObserverOptions = {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
};

function useIntersectionObserver<T extends HTMLElement>(
  ref: RefObject<T>,
  options: IntersectionObserverOptions = {}
): IntersectionObserverEntry | null {
  const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);

  useEffect(() => {
    const element = ref.current;
    const observer = new IntersectionObserver(([entry]) => {
      setEntry(entry);
    }, options);

    __TOKEN_17__ (element) observer.observe(element);

    __TOKEN_18__ () => {
      __TOKEN_19__ (element) observer.unobserve(element);
    };
  }, [ref, options]);

  return entry;
}

// Usage example
// const imgRef = useRef<HTMLImageElement>(null);
// const entry = useIntersectionObserver(imgRef, { threshold: 0.1 });
// const isVisible = entry?.isIntersecting;
// useEffect(() => {
//   if (isVisible) imgRef.current.src = imgRef.current.dataset.src;
// }, [isVisible]);