@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
36 lines (35 loc) • 1.31 kB
JavaScript
"use client";
import { useEffect, useEffectEvent, useRef, useState } from "react";
//#region packages/@mantine/hooks/src/use-scroll-direction/use-scroll-direction.ts
function useScrollDirection() {
const [lastScrollTop, setLastScrollTop] = useState(0);
const [scrollDirection, setScrollDirection] = useState("unknown");
const [isResizing, setIsResizing] = useState(false);
const resizeTimerRef = useRef(void 0);
const handleScroll = useEffectEvent(() => {
if (isResizing) return;
const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
setScrollDirection(currentScrollTop < lastScrollTop ? "up" : "down");
setLastScrollTop(currentScrollTop);
});
useEffect(() => {
const handleResize = () => {
setIsResizing(true);
window.clearTimeout(resizeTimerRef.current);
resizeTimerRef.current = window.setTimeout(() => {
setIsResizing(false);
}, 300);
};
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("scroll", handleScroll);
window.removeEventListener("resize", handleResize);
clearTimeout(resizeTimerRef.current);
};
}, []);
return scrollDirection;
}
//#endregion
export { useScrollDirection };
//# sourceMappingURL=use-scroll-direction.mjs.map