Categories
React Answers

How to Use the React setState Hook from Scroll Event Listener?

Spread the love

Sometimes, we want to use the React setState hook from scroll event listener.

In this article, we’ll look at how to use the React setState hook from scroll event listener.

Use the React setState Hook from Scroll Event Listener

To use the React setState hook from scroll event listener, we can call state setter functions from within in the scroll event handler.

For instance, we write:

import React, { useEffect, useRef, useState } from "react";

export default function App() {
  const prevScrollY = useRef(0);
  const [goingUp, setGoingUp] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      if (prevScrollY.current < currentScrollY && goingUp) {
        setGoingUp(false);
      }
      if (prevScrollY.current > currentScrollY && !goingUp) {
        setGoingUp(true);
      }

      prevScrollY.current = currentScrollY;
      console.log(goingUp, currentScrollY);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });

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

  return (
    <div>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </div>
  );
}

We have the prevScrollY ref to store the previous scroll distance without trigger rerendering.

Then we define the goingUp state to set whether we’re scrolling up or down if it’s true or false respectively.

In the useEffect callback, we have the handleScroll function that gets the vertical scroll distance with window.scrollY.

And we compare that to prevScrollY.current to check if we’re scrolling up or down.

We set goingUp by calling setGoingUp in each case.

Then we set prevScrollY.current to currentScrollY after we did the comparison.

Finally, we log the scroll distance and the value of goingUp.

To use it as the scroll listener, we call window.addEventListener with it.

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

Now when we scroll up or down, we should see the the value of goingUp and the vertical scroll distance logged.

Conclusion

To use the React setState hook from scroll event listener, we can call state setter functions from within in the scroll event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *