2 mins read


Custom React Hook for using Intersection Observer:- useIntersectionObserver


Implementation

 
import { useEffect, useState, useRef } from 'react';
 
interface IntersectionObserverOptions {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}
 
interface IntersectionObserverEntry {
  isIntersecting: boolean;
  intersectionRatio: number;
}
 
const useIntersectionObserver = (
  targetRef: React.RefObject<Element>,
  options?: IntersectionObserverOptions
): IntersectionObserverEntry => {
  const [entry, setEntry] = useState<IntersectionObserverEntry>({
    isIntersecting: false,
    intersectionRatio: 0,
  });
 
  const observerRef = useRef<IntersectionObserver | null>(null);
 
  useEffect(() => {
    const target = targetRef.current;
    if (!target) return;
 
    const observer = new IntersectionObserver(
      ([entry]) => setEntry(entry),
      options
    );
 
    observer.observe(target);
    observerRef.current = observer;
 
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
    };
  }, [targetRef, options]);
 
  return entry;
};
 
export default useIntersectionObserver;