以下の内容はhttps://uga-box.hatenablog.com/entry/2021/01/12/000000より取得しました。


【Next.js】isFallbackの位置の注意

Reactのフックを使っていたら以下のエラーが発生した

Error: Rendered more hooks than during the previous render.

ブラウザのコンソールには直前に以下のログがでていて

Warning: React has detected a change in the order of Hooks called by SamplePage. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks

リンクがあるので読むと「React はフックが呼ばれる順番に依存している」ので、毎回同じ順序、同じ回数だけ実行しなければないとのこと

ja.reactjs.org

実装で問題だったのはNext.jsのisFallbackの機能を使っている箇所

export default function SamplePage(props: Props) {
  const router = useRouter();
  const { isFallback, query } = router;
  if (isFallback) {
    return <div>Loading...</div>;
  }
  const { currentUser } = useContext(AuthContext);
  const [foo, setFoo] = useState<string>("");
  const [bar, setBar] = useState<string>("");

}

isFallbackの条件によってそれより下のフックが呼ばれない場合があり、フックが呼ばれる回数がレンダリングのたびに変わっていたのが原因だった

わけあってこうしていたのだが、すべてのフックが呼ばれた後にローディング中を返すようにしたらエラーと警告が解消された

  const router = useRouter();
  const { isFallback, query } = router;
  const { currentUser } = useContext(AuthContext);
  const [foo, setFoo] = useState<string>("");
  const [bar, setBar] = useState<string>("");
  if (isFallback) {
    return <div>Loading...</div>;
  }

わけあっての部分は考え直す

参考

isFallbackについて
Basic Features: Data Fetching | Next.js




以上の内容はhttps://uga-box.hatenablog.com/entry/2021/01/12/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14