UNPKG

@wojtekmaj/react-hooks

Version:

A collection of React Hooks.

22 lines (21 loc) 820 B
import { useCallback, useRef, useState } from 'react'; import useEventListener from './useEventListener.js'; const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; /** * Returns current scroll top direction. * * @returns {Direction | null} Scroll top direction */ export default function useScrollTopDirection() { const prevScrollTop = useRef(); const [direction, setDirection] = useState(isBrowser ? 'still' : null); const onScroll = useCallback(() => { const { scrollY } = window; if (prevScrollTop.current !== undefined) { setDirection(prevScrollTop.current < scrollY ? 'down' : 'up'); } prevScrollTop.current = scrollY; }, []); useEventListener(isBrowser ? document : null, 'scroll', onScroll); return direction; }