🌟

useEffect なしで window.scrollY 使う

2022/07/13に公開

別に window.scrollY じゃなくてもいいんだけど

import { useSyncExternalStore } from "react";

function subscribe(callback: () => void): () => void {
  window.addEventListener("scroll", callback);
  return () => {
    window.removeEventListener("scroll", callback);
  };
}

export function useScrollY(): number {
  return useSyncExternalStore(
    subscribe,
    () => window.scrollY,
    () => 0
  );
}

Discussion