Skip to content

useWindowScrollPosition

Get window scroll position of Y axis or X axis

Rizki Maulana Citra

Created by / Rizki Maulana Citra

JS
export default function useWindowScrollPosition() {
  const [pos, setPos] = useState({ y: 0, x: 0 })

  const listener = useCallback(() => {
    setPos({ x: window.scrollX, y: window.scrollY })
  }, [])

  useEffect(() => {
    window.addEventListener('scroll', listener)

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

  return pos
}

Usage

This can be use if you want to apply style to your sticky navbar, such as border.

JSX
export default function LovelyComponent() {
  const { y } = useWindowScrollPosition()

  return <div className={clsx(y > 100 && 'border-b-1 border-b-gray-800')}></div>
}
Edit on GitHub