Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scroll position with NextJS

I want to know if the user has scrolled or not to update the UI in NextJS. I have the following code, all the examples I have found have the same code:

  const [scrollY, setScrollY] = useState(0);

  const onScroll = (event) => {
    const { pageYOffset, scrollY } = window;
    console.log("yOffset", pageYOffset, "scrollY", scrollY);
    setScrollY(window.pageYOffset);
  };

  useEffect(() => {
    document.body.addEventListener("scroll", onScroll, { passive: true });
    // remove event on unmount to prevent a memory leak
    () => document.removeEventListener("scroll", onScroll, { passive: true });
  }, []);

But the scroll does not get updated, neither with document nor window. I always get the same output:

enter image description here

Any suggestion? Thanks:)

like image 651
gtech Avatar asked Sep 01 '26 01:09

gtech


1 Answers

onScroll function destroyed and created again on every re-render when states changes so its object id change too. and the one defined on useEffect shouldn't be changed.

You need to use useCallback to prevent this behavior and wrap onScroll in it.

and also addEventListener to the window, because you are reading pageYOffset, scrollY from window on the onScroll function

  const onScroll = useCallback(event => {
      const { pageYOffset, scrollY } = window;
      console.log("yOffset", pageYOffset, "scrollY", scrollY);
      setScrollY(window.pageYOffset);
  }, []);

  useEffect(() => {
    //add eventlistener to window
    window.addEventListener("scroll", onScroll, { passive: true });
    // remove event on unmount to prevent a memory leak with the cleanup
    return () => {
       window.removeEventListener("scroll", onScroll, { passive: true });
    }
  }, []);
like image 120
Chemi Adel Avatar answered Sep 03 '26 16:09

Chemi Adel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!