@etsoo/react
Version:
TypeScript ReactJs UI Independent Framework
54 lines (53 loc) • 1.71 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWindowScroll = void 0;
const react_1 = __importDefault(require("react"));
/**
* Detect window scroll
* @returns Scroll location
*/
const useWindowScroll = () => {
// State
const [pos, setPos] = react_1.default.useState({
x: window.scrollX,
y: window.scrollY
});
react_1.default.useEffect(() => {
let ticking = false;
let lastPos;
let requestAnimationFrameSeed = 0;
const scrollHandler = () => {
lastPos = {
x: window.scrollX,
y: window.scrollY
};
if (!ticking) {
requestAnimationFrameSeed = window.requestAnimationFrame(() => {
ticking = false;
requestAnimationFrameSeed = 0;
if (lastPos.x != pos.x || lastPos.y != pos.y) {
setPos(lastPos);
}
});
ticking = true;
}
};
window.addEventListener("scroll", scrollHandler, {
passive: true,
capture: false
});
return () => {
// Cancel animation frame
if (requestAnimationFrameSeed > 0)
window.cancelAnimationFrame(requestAnimationFrameSeed);
// Remove scroll event
window.removeEventListener("scroll", scrollHandler);
};
}, []);
// Return
return pos;
};
exports.useWindowScroll = useWindowScroll;