1
1

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の使い方を確認した話

1
Posted at

はじめに

CodexでTODOアプリなどを作りながら、Reactの機能を一つずつ整理しています。
今回は、useEffect の使い方と状態更新の仕組みについて、備忘録としてまとめます。

構文

useEffect はレンダリング後に任意の処理を実行するためのHookです。

useEffect(処理, 依存配列);

依存配列の設定により、処理が発火するタイミングをコントロールできます。

使い方

1. レンダリングごとに毎回実行する

依存配列を指定しないと、useStateなどでレンダリングするごとに毎回処理が実行されます。

useEffect(() => {
    console.log("毎回");
});

2. 初回のレンダリングだけ実行する

依存配列を空配列にすると、画面の初回表示時のみ処理が実行されます。

useEffect(() => {
    console.log("初回だけ");
}, []);

API取得やlocalStorage読込に使用されます。

3. 特定の値が操作されたときに実行する

依存配列に特定の値を設定すると、それが操作されたときに処理が実行されます。

useEffect(() => {
    console.log("count changed");
}, [count]);

値の保存や再計算、処理実行の通知に使用されます。

おわりに

使い方のうち、頻繁に使用されるのは2,3の認識です。
useStateとの棲み分けを、下記のようにまとめておきます。

useStateはデータを持つためのHook
useEffectはデータが変わったときに処理を追加するHook

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?