How to Get Scroll Position with React?

Sometimes, we want to get scroll position with React.

In this article, we’ll look at how to get scroll position with React.

Get Scroll Position with React

To get scroll position with React, we can add a scroll listener to window.

For instance, we write:

import { useEffect, useState } from "react";

export default function App() {
  const [scrollPosition, setScrollPosition] = useState(0);
  const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);

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

  return (
    <div className="App">
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>lorem ipsum {scrollPosition}</p>
        ))}
    </div>
  );
}

to create the scrollPosition state with the useState hook.

Then we add the handleScroll function that takes the scroll position with the window.pageYOffset property.

Then we call setScrollPosition to position, which is assigned to window.payeYOffset.

Next, we call the useEffect hook with a callback that calls window.addEventListener to add the scroll event listener.

We return a function that calls window.removeEventListener to remove the event listener when we unmount the component.

Now when we scroll up and down, we should see the scrollPosition in the rendered text.

Conclusion

To get scroll position with React, we can add a scroll listener to window.