1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactでスクロールを検知して処理をする[クリーンアップ関数]

Last updated at Posted at 2024-12-25

Reactでスクロールを検知して処理をする

やりたいこと

ユーザーが画面下までスクロールしたことを検知してなんらかの処理を行う

実装

  useEffect(() => {
    const handleScroll = () => {
      const userPosition = window.scrollY;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;

      if (userPosition + windowHeight >= documentHeight) {
        doSomething();
      }
    };

    window.addEventListener("scroll", handleScroll);

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

解説

まずはwondow.addEventListenerでスクロール位置を関します。
スクロールされる度にhandleScrollが呼び出されます。

window.addEventListener("scroll", handleScroll);

以下がhandleScrollの中身です。
ユーザーのスクロール位置、画面の幅を取得します。

const userPosition = window.scrollY; //ユーザーの位置を取得
const windowHeight = window.innerHeight; //ユーザーの画面領域を取得(端末の表示できる画面)
const documentHeight = document.documentElement.scrollHeight; //アプリの全領域を取得

アプリの全領域よりもユーザーのスクロール位置+ユーザーの画面の表示領域が大きい場合、画面最下部までスクロールされたと判断する

if (userPosition + windowHeight >= documentHeight) {
    doSomething();
}

最後に以下の処理が重要です。
Reactのクリーンアップ関数でコンポーネントがアンマウントされた後にスクロールの監視をやめます。
この処理をしないとhandleScrollが発火した後も、handleScrollを繰り返し続けます。

return () => {
  window.removeEventListener("scroll", handleScroll);
};

用語の解説
クリーンアップ関数...useEffectが実行される直前もしくは、コンポーネントがアンマウントされる時に実行される関数。
アンマウント...DOMからコンポーネントが削除されること

最後に

クリーンアップ関数の必要性&存在を知らずに永遠と繰り返される処理に詰まってしまいましたが、Reactの勉強になりました。
この記事が誰かの助けになれば幸いです。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?