useScroll

NEW

React hook to track and manipule the scroll position of a web page.

import { useState, useLayoutEffect } from 'react'

export const useScroll = () => {
  const [position, setPosition] = useState({
    x: 0,
    y: 0,
  })

  const handleScroll = () => {
    setPosition({
      x: window.scrollX,
      y: window.scrollY,
    })
  }

  useLayoutEffect(() => {
    window.addEventListener('scroll', handleScroll)

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

  return { position, scrollTo: window.scrollTo }
}

React 16.8 or higher

  • Name
    position
    Type
    object
    Description

    Indicates the current scroll position of the window.

  • Name
    position.x
    Type
    number
    Description

    The current horizontal scroll position of the window.

  • Name
    position.y
    Type
    number
    Description

    The current vertical scroll position of the window.

  • Name
    scrollTo
    Type
    function
    Description

    Allows you to scroll to a specified position.

import { useScroll } from './hooks/useScroll'

const App = () => {
  const { position, scrollTo } = useScroll()

  return (
    <div
      style={{
        height: window.innerHeight,
        width: window.innerWidth,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'column',
      }}
    >
      <p>x: {position.x}</p>
      <p>y: {position.y}</p>
      <button onClick={() => scrollTo({ top: 0, behavior: 'smooth' })}>
        Scroll to top
      </button>
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Track the scroll position to make a header sticky when the user scrolls past a certain point
  • Load more content when the user scrolls near the bottom of the page
  • Trigger animations based on the user's scroll position
  • Highlight navigation items based on the section currently in view
  • Show a button that scrolls the user back to the top of the page