0
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 1 year has passed since last update.

useEffectを画面表示時(マウント時)のみ発火させる方法

Posted at

まぁ何番煎じだよって気もしますが復習用

useEffectの第二引数に空配列を指定することで画面表示時に発火するようになります。

useEffect(() => { 
    console.log(test)
}, []);

useStateの値を指定した場合はstateが更新されたとき(setTest()呼ばれたとき)に発火するようになります。

const [test, setTest] = useState('');

useEffect(() => { 
    console.log(test);
}, [test]);

useStateの第一引数にはstateが更新されたときの関数を渡しますが、非同期関数は渡せません、内部で非同期関数を呼ぶようにしましょう。
NG

useEffect(async () => {
    console.log(test);
  }, [test]);

OK

useEffect(() => {
    async function test() {
      console.log(test);
    }
  }, [test]);
0
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
0
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?