-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathuseNearScreen.js
49 lines (42 loc) · 1.04 KB
/
useNearScreen.js
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
import {useState, useEffect} from 'react'
const targetCallbacks = new WeakMap()
const observerP =
typeof window !== 'undefined' &&
Promise.resolve(
typeof window.IntersectionObserver === 'undefined' &&
import('intersection-observer')
).then(
() =>
new window.IntersectionObserver(entries => {
entries
.filter(e => e.isIntersecting)
.map(e => targetCallbacks.get(e.target))
.filter(Boolean)
.forEach(cb => cb())
})
)
function whenIntersecting(target, cb) {
function unsubscribe() {
observerP.then(observer => {
observer.unobserve(target)
targetCallbacks.delete(target)
})
}
observerP.then(observer => {
observer.observe(target)
targetCallbacks.set(target, () => {
unsubscribe()
cb()
})
})
return unsubscribe
}
export const useNearScreen = ({ref}) => {
const [show, setShow] = useState(false)
useEffect(
() =>
ref && ref.current && whenIntersecting(ref.current, () => setShow(true)),
[ref]
)
return show
}