-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactIntersectionObserver.tsx
42 lines (31 loc) · 1.1 KB
/
ReactIntersectionObserver.tsx
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
import { useEffect, useRef, useState } from 'react';
// store all observers
let observers = {};
// store all different callbacks
const callbacks = {};
function observe(entries, opts: string) {
entries.forEach((entry, i) => {
if (entry.isIntersecting && typeof callbacks[opts][i] === 'function') callbacks[opts][i]();
});
}
type result = [(node: Element | null) => void, boolean];
export function useInView(options = {}): result {
const opts = JSON.stringify(options);
if (typeof observers[opts] === 'undefined' && typeof window !== 'undefined') {
observers[opts] = new IntersectionObserver(entries => observe(entries, opts), options);
}
const ref = useRef<Element>(null) as React.MutableRefObject<Element>;
const [inView, setInView] = useState<boolean>(false);
useEffect(() => {
if (typeof callbacks[opts] === 'undefined') callbacks[opts] = [];
if (ref.current) {
callbacks[opts].push(() => {
if (inView === false) setInView(true);
});
observers[opts].observe(ref.current);
}
}, [ref]);
// @ts-ignore
return [ref, inView];
}
export default useInView;