Gatlin.io Icon
Image of Austin Gatlin's face
March 7, 2022

React Scroll to Top Button

A simple scroll-to-top button in React using the window.scroll API.

function ScrollToTopButton() {
  const handleClick = () => {
    window.scroll({ top: 0, behavior: 'smooth' })
  }

  return <button onClick={handleClick}>^</button>
}

If you want to hide the button when at the top of the page, things get a little more tricky, since there can be a performance impact to simple solutions. You will want to explore debouncing or throttling functions if you want to achieve good performance. Also, you will not want to add event listeners every render. One "cheap" way to solve this is to capture the window in a local variable. In Next.js window is not present on the server, but is always present inside the client-side useEffect hook. Add a console.log inside each effect to see that setW is called approximately twice, while setY is called thousands of times.

function X() {
  const [w, setW] = useState<Window | undefined>()
  const [y, setY] = useState(0)

  useEffect(() => {
    setW(window)
  }, [w])

  useEffect(() => {
    if (w) w.addEventListener('scroll', () => setY(w.scrollY))
  })

  render <>...</>
}