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?

useEffect | AIと公式ドキュメントから学ぶReact

Posted at

使い方

1. マウント時に一度だけ実行

React.useEffect(() => console.log("Hello"), []);
  • 空の依存配列 [] を渡すと 初回レンダー後に一度だけ 実行。
    console.log("Hello") がページ読み込み時に走る。

2. 値が変わるたびにタイトルを更新

React.useEffect(() => { document.title = `クリック数:${count}`; }, [count]);
  • count を依存配列に入れると count が変わるたび に実行。
    document.title が最新クリック数を表示。

useEffect の役割

レンダー後に起こす「副作用(エフェクト)」を 安全に管理 するフック。

  • レンダー外の処理をまとめられる
    DOM 操作や API 通信など、画面描画とは別の動きをここに集約。

  • 依存配列で実行タイミングを制御
    いつ実行するかを [] の中身で宣言的に指定できる。

  • クリーンアップで後始末が出来る
    監視の解除やタイマーの停止を簡単に書ける。

レンダー外の処理をまとめられるとは?

React は「UI = 状態の結果」を描くライブラリ。
でも DOM 直接操作や外部 API 取得 など “UI 以外” の処理も必要です。
useEffect に書けば「レンダー後にやること」が一目で分かり、複数箇所に散らばるのを防げます。

例:タイマーを設置してカウントアップ

// App.jsx
import React from "react";

export default function App() {
  const [sec, setSec] = React.useState(0);                           // 0 秒から開始

  React.useEffect(() => {                                            // レンダー後に実行
    const id = setInterval(() => setSec(s => s + 1), 1000);          // 1 秒ごと +1
    return () => clearInterval(id);                                  // ← クリーンアップ:アンマウント時にタイマー停止
  }, []);                                                            // [] なので一度だけ

  return <p>{sec} 秒経過</p>;
}

useEffect のベストプラクティス

  • 依存配列を正しく書く
    参照している値を漏れなく入れる。ESLint の警告は無視しない。

  • クリーンアップでリソースを解放
    タイマー・イベントリスナ・サブスクは return () => … で必ず解除。

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?