@kiwicom/orbit-components
Version:
Orbit-components is a React component library which provides developers with the easiest possible way of building Kiwi.com’s products.
32 lines • 841 B
JavaScript
import { useState, useEffect, useRef, useCallback } from "react";
const useIntersect = ({
root = null,
rootMargin,
threshold = 0
} = {}) => {
const [entry, updateEntry] = useState(null);
const [node, setNode] = useState(null);
const ref = useCallback(el => {
setNode(el);
}, []);
const observer = useRef(null);
useEffect(() => {
if ("IntersectionObserver" in window === false) return () => {};
observer.current = new window.IntersectionObserver(([ent]) => updateEntry(ent), {
root,
rootMargin,
threshold
});
const {
current: currentObs
} = observer;
if (node) currentObs?.observe(node);
return () => currentObs?.disconnect();
}, [node, root, rootMargin, threshold]);
return {
ref,
entry,
observer: observer.current
};
};
export default useIntersect;