UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

40 lines (39 loc) 1.45 kB
import { useEffect, useCallback, useState } from "react"; import { noop } from "../utils/noop"; var config = { root: null, rootMargin: "0px 0px 0px 0px", threshold: [0, 1], }; /** * * useIntersectionObserverRef hook * * Returns a mutation observer for a React Ref and fires a callback * * @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation * @param {IntersectionObserverInit} options * @see https://react-hooks.org/docs/useIntersectionObserverRef */ function useIntersectionObserverRef(callback, options) { if (options === void 0) { options = config; } var _a = options.root, root = _a === void 0 ? null : _a, rootMargin = options.rootMargin, threshold = options.threshold; var _b = useState(null), node = _b[0], setNode = _b[1]; useEffect(function () { // Create an observer instance linked to the callback function if (node && callback) { var observer_1 = new IntersectionObserver(callback, options); // Start observing the target node for configured mutations observer_1.observe(node); return function () { observer_1.disconnect(); }; } return noop; }, [node, callback, root, rootMargin, threshold, options]); var ref = useCallback(function (nodeElement) { setNode(nodeElement); }, []); return [ref]; } export { useIntersectionObserverRef };