Reactガイドを読んでいくその260

これは

Reactのガイドを読んでいく記事です。

ガイドのリンク

ja.reactjs.org

フックのルール

解説

Reactは一つのコンポーネント内で複数のstateや副作用を使うことができるのはこれまでに学んできた。
Reactはフックが呼ばれる順番に依存してuseStateの呼び出しがどのstateに対応するのか知ることができる。
フックで呼び出すのがトップレベルのみでなければならない理由として、
条件分岐のなかでフックを呼び出した場合、Reactは二つ目のuseStateの呼び出しに何を返せばいいのかわからなくなってしまうというものがある。

// 🔴 We're breaking the first rule by using a Hook in a condition
  if (name !== '') {
    useEffect(function persistForm() {
      localStorage.setItem('formData', name);
    });
  }

上記のようなコードの場合以下のようになる

useState('Mary')           // 1. Read the name state variable (argument is ignored)
// useEffect(persistForm)  // 🔴 This Hook was skipped!
useState('Poppins')        // 🔴 2 (but was 3). Fail to read the surname state variable
useEffect(updateTitle)     // 🔴 3 (but was 4). Fail to replace the effect

次回は独自フックの作成についてみていきます。

今日はここまで。