1 | import { useEffect } from 'react';
|
---|
2 | import { isBrowser, off, on } from './misc/util';
|
---|
3 | import useRafState from './useRafState';
|
---|
4 | var useWindowScroll = function () {
|
---|
5 | var _a = useRafState(function () { return ({
|
---|
6 | x: isBrowser ? window.pageXOffset : 0,
|
---|
7 | y: isBrowser ? window.pageYOffset : 0,
|
---|
8 | }); }), state = _a[0], setState = _a[1];
|
---|
9 | useEffect(function () {
|
---|
10 | var handler = function () {
|
---|
11 | setState(function (state) {
|
---|
12 | var pageXOffset = window.pageXOffset, pageYOffset = window.pageYOffset;
|
---|
13 | //Check state for change, return same state if no change happened to prevent rerender
|
---|
14 | //(see useState/setState documentation). useState/setState is used internally in useRafState/setState.
|
---|
15 | return state.x !== pageXOffset || state.y !== pageYOffset
|
---|
16 | ? {
|
---|
17 | x: pageXOffset,
|
---|
18 | y: pageYOffset,
|
---|
19 | }
|
---|
20 | : state;
|
---|
21 | });
|
---|
22 | };
|
---|
23 | //We have to update window scroll at mount, before subscription.
|
---|
24 | //Window scroll may be changed between render and effect handler.
|
---|
25 | handler();
|
---|
26 | on(window, 'scroll', handler, {
|
---|
27 | capture: false,
|
---|
28 | passive: true,
|
---|
29 | });
|
---|
30 | return function () {
|
---|
31 | off(window, 'scroll', handler);
|
---|
32 | };
|
---|
33 | }, []);
|
---|
34 | return state;
|
---|
35 | };
|
---|
36 | export default useWindowScroll;
|
---|