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