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?

「React has detected a change in the order of Hooks called by〜」のエラーの対処法

Posted at

Reactで「React has detected a change in the order of Hooks called by〜 . This will lead to bugs and errors if not fixed.」のエラーが発生した場合の対処法です。

上記エラーは、useStateなどのHooksが呼び出される順序が変わったときに発生するそうです。

Reactでは、Hooksはトップレベルで呼び出す必要があります。

フックをループや条件分岐、あるいはネストされた関数内で呼び出してはいけません。代わりに、あなたの React の関数のトップレベルでのみ、あらゆる早期 return 文よりも前の場所で呼び出してください。これを守ることで、コンポーネントがレンダーされる際に毎回同じ順番で呼び出されるということが保証されます。これが、複数回 useState や useEffect が呼び出された場合でも React がフックの状態を正しく保持するための仕組みです

参考:https://ja.legacy.reactjs.org/docs/hooks-rules.html

そのため、以下のようにif文や下記のような早期return文の後にHooksを書くとHooksの順序が変わってしまいエラーが発生します。

import { useEffect, useState } from "react";

const Sample = ({ count }: { count: number }) => {
  const [flag1, setFlag1] = useState(true);
  if (count === 0) {
    return <></>;
  }

  const [flag2, setFlag2] = useState(true);

  return <>{count}</>;
};

export default Sample;

対処法その1:Hooksは関数のトップレベル、早期return文より前に書く

Hooksは条件分岐内や早期return文の後ではなく、トップレベルに書く必要があります。
下記のように、早期return文より前にHooksを書けばエラーは発生しなくなります。

"use state";

import { useEffect, useState } from "react";

const Sample = ({ count }: { count: number }) => {
  const [flag1, setFlag1] = useState(true);
  const [flag2, setFlag2] = useState(true);
  if (count === 0) {
    return <></>;
  }

  return <>{count}</>;
};

export default Sample;

対処法その2:コンポーネントとして切り出す

下記のように、コンポーネントとして切り出した場合もエラーは発生しません。

import { useEffect, useState } from "react";

const Parent = ({ count }: { count: number }) => {
  const [flag1, setFlag1] = useState(true);
  if (count === 0) {
    return <></>;
  }

  return <Children count={count} />;
};

const Children = ({ count }: { count: number }) => {
  const [flag2, setFlag2] = useState(true);
  return <>{count}</>;
};

export default Parent;

そもそも

VSCodeでeslintの設定されていれば、コード書いているときに以下のようにエラーを表示してくれるので気付けます。
image.png

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?