'use client'; import { useState, useEffect } from 'react'; export type ScrollDirection = 'up' | 'down'; /** * A hook to detect the scroll direction. * It uses requestAnimationFrame for performance, comparing the current scroll position * with the previous one to determine if the user is scrolling up or down. * * @returns {ScrollDirection | null} The current scroll direction ('up' or 'down'), or null on the initial render. */ export function useScrollDirection(): ScrollDirection | null { const [scrollDirection, setScrollDirection] = useState(null); useEffect(() => { let lastScrollY = window.pageYOffset; let ticking = false; const updateScrollDirection = () => { const scrollY = window.pageYOffset; if (Math.abs(scrollY - lastScrollY) < 10) { ticking = false; return; } setScrollDirection(scrollY > lastScrollY ? 'down' : 'up'); lastScrollY = scrollY > 0 ? scrollY : 0; ticking = false; }; const onScroll = () => { if (!ticking) { window.requestAnimationFrame(updateScrollDirection); ticking = true; } }; window.addEventListener('scroll', onScroll); return () => window.removeEventListener('scroll', onScroll); }, []); return scrollDirection; }