Invalid hook call error in Next.js
A quick one. I keep getting this intermittent error when developing React applications using Next.JS – particularly when changing branches but it happens at other times too.
Unhandled Runtime Error
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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
The error message is extremely misleading. I spent hours looking at my hooks and then trying to find inconsistencies in versions of React. The actual solution is to delete the .next folder in the root of your application and restart your application. So the command would be
rm -rf .next
If that doesn’t work then it is worth deleting your node_modules folder and reinstalling your packages. So that would be
rm -rf node_modules npm install
In my experience just deleting the .next folder is enough to fix this but a module reinstall is always worth trying if you are struggling and maybe delete packages-lock.json. The important point is that it is nothing to do with hooks so don’t waste your time pondering them if you are getting this error intermittently.