Get scroll position with NextJS

gte*_*ech 3 scroll reactjs next.js

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 });
  }, []);
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

Any suggestion? Thanks:)

Che*_*del 11

onScroll当状态发生变化时,函数会在每次重新渲染时被销毁并再次创建,因此它的对象 ID 也会发生变化。并且 useEffect 上定义的值不应更改。

您需要使用 useCallback 来防止这种行为并将onScroll其包装起来。

并且还将EventListener 添加window,因为您正在从onScroll函数读取 pageYOffset scrollYwindow

  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 });
    }
  }, []);
Run Code Online (Sandbox Code Playgroud)