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?

More than 3 years have passed since last update.

useEffect 第二引数の使い分け

Last updated at Posted at 2021-05-02

投票アプリ作成中、よくわからない警告に遭遇(Part2)

投票アプリ以外でも、時々、今回の警告は見たことがあった。。。

React Hook useEffect has a missing dependency: 'email'. Either include it or remove the dependency array react-hooks/exhaustive-deps
(日本語)React Hook useEffectに依存関係がありません: 'email'。それを含めるか、依存関係配列react-hooks / exhaustive-depsを削除します

大前提として、useEffectについて

第一引数には、副作用として実行する関数を与える。
useEffectに指定することで、副作用は、コンポーネントの描写が終わった後に実行される。

第二引数によって、副作用を実行する頻度を設定できる。
第二引数を与えなかった場合、コンポーネントの描写後、毎回実行。
🔴第二引数に空の配列を与えた場合には、初回描写時にのみ実行。
🔵第二引数に配列を与え、要素として変数を指定すると、指定した変数に変更があった場合のみ実行。

警告が出る理由

第2引数を指定していないから。

今回、以下のコードのように、

🔴第二引数に空の配列を与えた場合には、初回描写時にのみ実行。

としていた。

  // ユーザー情報を取得
  useEffect(() => {
    firebase
      .firestore()
      .collection("users")
      .where("email", "==", email)
      .onSnapshot((snapshot) => {
        const getUsers = snapshot.docs.map((doc) => {
          return {
            ...doc.data(),
            docid: doc.id,
          };
        });
        setUsers(getUsers);
      });
  }, []);

対処法

以下のコードのように、

🔵第二引数に配列を与え、要素として変数を指定すると、指定した変数に変更があった場合のみ実行。

とすることで、警告は消えた。

}, [email]);

その他の警告と対処

React Hook useEffect has missing dependencies: 'history.location.state.birthday', 'history.location.state.email', 'history.location.state.gender', 'history.location.state.password', and 'history.location.state.username'. Either include them or remove the dependency array react-hooks/exhaustive-deps

(対処)
こちらも 🔴第二引数を空の配列 としていたため、
以下のように、 🔵変数を指定した ことで、警告は消えた。

  }, [history]);

React Hook useEffect has missing dependencies: 'email', 'question.answer1Id', 'question.answer2Id', and 'question.docid'. Either include them or remove the dependency array react-hooks/exhaustive-deps

(対処)
こちらも 🔴第二引数を空の配列 としていたため、
以下のように、 🔵変数を指定した ことで、警告は消えた。

  }, [email, question]);

今後は、、、

第二引数が、
⭐空の配列が適している場合、変数を指定する場合⭐
これらを適切に使い分けれるように、まだまだ勉強が必要だ。。。

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?