-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseIntersection.ts
59 lines (53 loc) · 1.7 KB
/
useIntersection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { useEffect, useRef, useState } from "react";
type OnIntersection = (
isIntersecting: boolean,
ob: IntersectionObserver
) => boolean | void;
const DefaultOptions: IntersectionObserverInit = {
root: null,
threshold: 0,
};
// Return false here to disconnect ob.
const DefaultOnIntersection: OnIntersection = (isIntersecting, _ob) => {
if (isIntersecting) return false;
};
/**
* Lazy Loading components with Intersection Observer API
* @param onIntersection default: disconnect observer.
* @param options default: `{root: null, threshold: 0}`
* @returns `[isIntersecting, ref]`
*
* @see https://dev.to/anxiny/custom-react-hook-useintersection-with-intersection-observer-4l4e
* @see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
*/
export function useIntersection(
onIntersection: OnIntersection = DefaultOnIntersection,
options: IntersectionObserverInit = DefaultOptions
) {
const [isIntersecting, setIsIntersecting] = useState(false);
const elemRef = useRef<null | Element | undefined>(null);
const setElem = (elem: any) => {
elemRef.current = elem;
};
useEffect(() => {
if (!elemRef.current) return;
let isUnmounted = false;
const ob = new IntersectionObserver(
([entry]) => {
if (isUnmounted) return;
const isElementIntersecting = entry.isIntersecting;
if (onIntersection(isElementIntersecting, ob) === false) {
ob.disconnect();
}
setIsIntersecting(isElementIntersecting);
},
{ ...options }
);
ob.observe(elemRef.current);
return () => {
ob.disconnect();
isUnmounted = true;
};
}, [options, onIntersection]);
return [isIntersecting, setElem] as const;
}