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?

useEffectの書き方の違い

Last updated at Posted at 2024-12-09

はじめに

マウントした時に実行したい、アンマウントされた時に実行したいといったときにuseEffectでの書き方が異なるので、備忘録としてまとめる。

useEffectの書き方

以下のパターンの時のuseEffectの書き方とまとめる。

  • 毎レンダリング時
  • 初回表示のみ
  • 依存配列の変更時
  • アンマウント時

毎レンダリング時

useEffect(() => {
  console.log('Component rendered');
});

初回表示のみ

useEffect(() => {
  console.log('Component mounted');
}, []);

依存配列の変更時

// dependencyの値が変更されるたびに実行される
useEffect(() => {
  console.log('Dependency changed');
}, [dependency]);

アンマウント時

useEffect(() => {
  return () => {
    console.log('Component will unmount');
  };
}, []);

まとめ

  • useEffectの第2引数(依存配列)に変数を指定するとその値が更新されるたびに実行される
  • 空配列にすると一回のみ
  • 何も指定しないと毎回実行される
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?