LoginSignup
3
5

More than 1 year has passed since last update.

[React] useEffectとaddEventListenerの代わりにuseEventを使ってみた

Last updated at Posted at 2022-02-11

Webの開発をしている時にuseEventというHookがあることを知ったので、
まとめるために記事にしました。
誰かのお役に立てれば、幸いです。

参考サイトのnpmには、

This hook cleans up your listeners automatically when it unmounts.

アンマウント時に自動でリスナーをクリーンナップをしてくれるようで、
少しはスッキリと書けるようになるみたいです。

書き比べてみる

画面をスクロールすると表示が変わるフックを書き換えてみたいと思います。

  const [isVisible, setIsVisible] = useState(true);
  const toggleVisibility = () => {
    window.scrollY > 300 ? setIsVisible(false) : setIsVisible(true);
  };

  useEffect(() => {
    window.addEventListener("scroll", toggleVisibility);
    return () => window.removeEventListener("scroll", toggleVisibility);
  }, []);

これをuseEvent で書き換えてみます。

  import useEvent from "@react-hook/event";

  const [isVisible, setIsVisible] = useState(true);
  const toggleVisibility = () => {
    globalThis.scrollY > 300 ? setIsVisible(false) : setIsVisible(true);
  };

  useEvent(globalThis, "scroll", toggleVisibility);

スッキリと書くことができました。

書き換えた時に、target となるところに、window だとエラーが出ました。
解決策は参考サイトにもありますが、クライアント側でwindow にあたるglobalThisを使うことで
エラーを回避しています。

参考にしたサイト

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5