17
5

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学習ログ No.6

17
Posted at

React学習メモ:useEffect

目的:副作用の実行

  • Reactコンポーネントの描画以外の処理を担当
  • API通信、DOM操作 (document.title)、タイマー (setTimeout)、イベントリスナー

最重要:依存配列(第2引数)

これで実行タイミングを制御する。

  • [] (空配列)

    • タイミング: 初回レンダリング後に1回だけ
    • 用途: 初期データの取得など、一度きりの処理
  • [value] (値あり)

    • タイミング: 初回 + 配列内のvalue変更された時
    • 用途: 特定のデータ(例: userId)に依存する処理
  • 指定なし

    • タイミング: 毎回のレンダリング後
    • 注意: 無限ループになりやすい。基本的に避ける

必須:クリーンアップ関数

  • 目的: メモリリーク防止のための後片付け
  • 書き方: useEffect内から**関数をreturn**する
  • 用途: setIntervalの解除 (clearInterval)、イベントリスナーの削除 (removeEventListener) など
useEffect(() => {
  // セットアップ処理
  const timerId = setInterval(tick, 1000);

  // クリーンアップ処理
  return () => clearInterval(timerId);
}, []);

注意点

  • 無限ループ: useEffect内でstateを更新し、依存配列を指定なしにするとループする。依存配列を正しく設定することが重要
17
5
1

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
17
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?