UNPKG

1.94 kBJavaScriptView Raw
1import { useState } from 'react';
2import useStableMemo from './useStableMemo';
3import useEffect from './useIsomorphicEffect';
4import useEventCallback from './useEventCallback';
5/**
6 * Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
7 * a DOM Element that returns it's entries as they arrive.
8 *
9 * @param element The DOM element to observe
10 * @param init IntersectionObserver options with a notable change,
11 * unlike a plain IntersectionObserver `root: null` means "not provided YET",
12 * and the hook will wait until it receives a non-null value to set up the observer.
13 * This change allows for easier syncing of element and root values in a React
14 * context.
15 */
16
17function useIntersectionObserver(element, callbackOrOptions, maybeOptions) {
18 var callback;
19 var options;
20
21 if (typeof callbackOrOptions === 'function') {
22 callback = callbackOrOptions;
23 options = maybeOptions || {};
24 } else {
25 options = callbackOrOptions || {};
26 }
27
28 var _options = options,
29 threshold = _options.threshold,
30 root = _options.root,
31 rootMargin = _options.rootMargin;
32
33 var _useState = useState(null),
34 entries = _useState[0],
35 setEntry = _useState[1];
36
37 var handler = useEventCallback(callback || setEntry); // We wait for element to exist before constructing
38
39 var observer = useStableMemo(function () {
40 return root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
41 threshold: threshold,
42 root: root,
43 rootMargin: rootMargin
44 });
45 }, [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
46 useEffect(function () {
47 if (!element || !observer) return;
48 observer.observe(element);
49 return function () {
50 observer.unobserve(element);
51 };
52 }, [observer, element]);
53 return callback ? undefined : entries || [];
54}
55
56export default useIntersectionObserver;
\No newline at end of file