UNPKG

@n0n3br/react-use-scroll-direction

Version:

A robust React hook to detect vertical scroll direction ('up', 'down', 'static') for any DOM element or the window.

72 lines (71 loc) 2.43 kB
// src/index.ts import { useState, useEffect, useRef, useCallback } from "react"; function useScrollDirection(ref, options) { const { threshold = 0, throttleDelay = 100 } = options || {}; const [scrollDirection, setScrollDirection] = useState("static"); const lastScrollPosition = useRef(0); const throttleTimeoutId = useRef(null); const getScrollY = useCallback(() => { if (ref && ref.current) { return ref.current.scrollTop; } return window.scrollY; }, [ref]); useEffect(() => { const targetElement = ref && ref.current ? ref.current : window; if (!targetElement) return; lastScrollPosition.current = getScrollY(); const handleScroll = () => { const currentScrollPosition = getScrollY(); const scrollDifference = currentScrollPosition - lastScrollPosition.current; if (Math.abs(scrollDifference) <= threshold) { return; } if (scrollDifference > 0) { setScrollDirection("down"); } else { setScrollDirection("up"); } lastScrollPosition.current = currentScrollPosition; }; const throttledHandleScroll = () => { if (throttleTimeoutId.current === null) { throttleTimeoutId.current = window.requestAnimationFrame(() => { handleScroll(); throttleTimeoutId.current = null; }); } }; const throttledHandleScrollWithDelay = () => { if (throttleTimeoutId.current === null) { throttleTimeoutId.current = window.setTimeout(() => { handleScroll(); throttleTimeoutId.current = null; }, throttleDelay); } }; const effectiveThrottledScrollHandler = throttleDelay > 0 && throttleDelay !== 100 ? throttledHandleScrollWithDelay : throttledHandleScroll; targetElement.addEventListener("scroll", effectiveThrottledScrollHandler, { passive: true }); return () => { targetElement.removeEventListener( "scroll", effectiveThrottledScrollHandler ); if (throttleTimeoutId.current !== null) { if (throttleDelay > 0 && throttleDelay !== 100) { clearTimeout(throttleTimeoutId.current); } else { cancelAnimationFrame(throttleTimeoutId.current); } throttleTimeoutId.current = null; } }; }, [ref, threshold, throttleDelay, getScrollY]); return scrollDirection; } export { useScrollDirection };