LoginSignup
13
1

More than 3 years have passed since last update.

Next.js で Invalid hooks エラーになったけど意味不明なときは npm run clean する

Posted at

Next.js で React hooks を使おうと思って意気揚々と useEffect() って書いて実行をしたら以下のようなエラーが出てしまって彷徨ってしまったときのメモ。

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

非常に丁寧なエラーメッセージで、解説記事もあり分かりやすい。のだけど、どう考えてもどれにも該当していない…なぜと頭を悩ませていたけど、実際は3番めの React app が重複して読み込まれているという症状だった。

Next.js で SSR するときには npm run serve を実行するが、そのときに生成される dist ディレクトリが原因。これがある状態で npm run dev でビルドすると重複してしまう。なので、どちらかに統一するのが良い。

単純に dist ディレクトリを消しても良いし、 npm run clean で余計なファイルを一括で削除しても良い。これで Next.js で React hooks を使うことができる。

13
1
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
13
1