Custom React Hook for using Intersection Observer:- useIntersectionObserver
Series: Custom React Hooks
Episodes: (10/10)
- Custom React Hook for Full Screen Mode
- Custom React Hook for Queue
- Custom React Hook for Array
- Custom React Hook for Event Listening
- Custom React Hook for using setInterval
- Custom React Hook for using setTimeout
- Custom react hook for client idle detection:- useIdle
- Custom react hook for checking client internet connection:- useOnlineStatus
- Custom react hook for API call:- useAsync
- 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;