reactjsscrollnext.js

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:)


Solution

  • 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 });
        }
      }, []);