-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
50 lines (40 loc) · 1.06 KB
/
index.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
50
'use strict'
let { useState, useEffect } = require('react')
let _throttle = require('lodash.throttle')
let supportsPassive = false
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true
},
})
window.addEventListener('testPassive', null, opts)
window.removeEventListener('testPassive', null, opts)
} catch (e) {}
let getPosition = () => ({
x: window.pageXOffset,
y: window.pageYOffset,
})
let defaultOptions = {
throttle: 100,
}
function useWindowScrollPosition(options) {
let opts = Object.assign({}, defaultOptions, options)
let [position, setPosition] = useState(getPosition())
useEffect(() => {
let handleScroll = _throttle(() => {
setPosition(getPosition())
}, opts.throttle)
window.addEventListener(
'scroll',
handleScroll,
supportsPassive ? { passive: true } : false
)
return () => {
handleScroll.cancel()
window.removeEventListener('scroll', handleScroll)
}
}, [])
return position
}
module.exports = useWindowScrollPosition