Snippet: useScrollDirection Custom Hook

Snippet

Back

useScrollDirection Custom Hook

logo for React.js

A custom React hook to detect user scroll direction

A useful React custom hook function called `useScrollDirection`, which will detect when the user scrolls up or down. A good use case would be when you want to show/hide the navigation bar.

// useScrollDirection.js
import { useEffect, useRef, useState } from 'react'

const THRESHOLD = 0

const useScrollDirection = () => {
  const [scrollDirection, setScrollDirection] = useState('up')

  const blocking = useRef(false)
  const prevScrollY = useRef(0)

  useEffect(() => {
    prevScrollY.current = window.pageYOffset

    const updateScrollDirection = () => {
      const scrollY = window.pageYOffset

      if (Math.abs(scrollY - prevScrollY.current) >= THRESHOLD) {
        const newScrollDirection =
          scrollY > prevScrollY.current ? 'down' : 'up'

        setScrollDirection(newScrollDirection);

        prevScrollY.current = scrollY > 0 ? scrollY : 0
      }

      blocking.current = false
    };

    const onScroll = () => {
      if (!blocking.current) {
        blocking.current = true
        window.requestAnimationFrame(updateScrollDirection)
      }
    }

    window.addEventListener('scroll', onScroll)

    return () => window.removeEventListener('scroll', onScroll)
  }, [scrollDirection])

  return scrollDirection
}

export default useScrollDirection

When you call this function, it will return a string value of 'up' or 'down' each time the user scrolls. You can edit the code to your liking and have it return whatever you want.

Loading...