react-use/src/useIntersection.ts
Kevin Norris d5f359f7e3 feat: useIntersection (#652)
React sensor hook that tracks the changes in the intersection of a target element with an ancestor element or with a top-level document's viewport, using the Intersection Observer API
2019-10-12 19:22:23 +11:00

31 lines
850 B
TypeScript

import { RefObject, useEffect, useState } from 'react';
const useIntersection = (
ref: RefObject<HTMLElement>,
options: IntersectionObserverInit
): IntersectionObserverEntry | null => {
const [intersectionObserverEntry, setIntersectionObserverEntry] = useState<IntersectionObserverEntry | null>(null);
useEffect(() => {
if (ref.current) {
const handler = (entries: IntersectionObserverEntry[]) => {
setIntersectionObserverEntry(entries[0]);
};
const observer = new IntersectionObserver(handler, options);
observer.observe(ref.current);
return () => {
if (ref.current) {
observer.disconnect();
}
};
}
return () => {};
}, [ref, options.threshold, options.root, options.rootMargin]);
return intersectionObserverEntry;
};
export default useIntersection;