UNPKG

1.21 kBJavaScriptView Raw
1import { useState } from 'react';
2import useStableMemo from './useStableMemo';
3import useEffect from './useIsomorphicEffect';
4/**
5 * Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
6 * a DOM Element.
7 *
8 * @param element The DOM element to observe
9 * @param init IntersectionObserver options
10 */
11
12export default function useIntersectionObserver(element, _temp) {
13 var _ref = _temp === void 0 ? {} : _temp,
14 threshold = _ref.threshold,
15 root = _ref.root,
16 rootMargin = _ref.rootMargin;
17
18 var _useState = useState(null),
19 entries = _useState[0],
20 setEntry = _useState[1];
21
22 var observer = useStableMemo(function () {
23 return typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(function (entries) {
24 return setEntry(entries);
25 }, {
26 threshold: threshold,
27 root: root,
28 rootMargin: rootMargin
29 });
30 }, [root, rootMargin, threshold && JSON.stringify(threshold)]);
31 useEffect(function () {
32 if (!element || !observer) return;
33 observer.observe(element);
34 return function () {
35 observer.unobserve(element);
36 };
37 }, [observer, element]);
38 return entries || [];
39}
\No newline at end of file