When I run eslint
on my next.js
application (or try to build it) it shows this error message;
error React Hook "useState" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render
I've made a copy of this component, and removed as much code as I can, and managed to retain the error. This is my code
"use client"
import { useState } from "react"
export default function Test() {
const [info, setInfo] = useState<number>(0)
for (let c1 = 0; c1 < 5; c1++) {
console.log(c1) // fails with or without this line
}
return <div>hello</div>
}
And it returns the above error.
It doesn't matter what's in the for
loop, but if I remove the loop altogether, it compiles fine, and doesn't complain.
If I replace the for loop with..
[0,1,2,4,5].forEach(c1=>{
console.log(c1)
})
Then it also compiles fine.
This has nothing to do with Next.js
, directly atleast.
Looks like there was a bug introduced in the package eslint-plugin-react-hooks
, which would report false positives. Here is the thread.
It will be fixed in the next release. You can install it using the command npm install eslint-plugin-react-hooks@next
, which installs the upcoming version.
You can also use the command npm ls --depth=Infinity
to see which depenendency exactly is being used by next.js