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.
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.
Share Improve this question asked Jan 31 at 13:24 Rich SRich S 3,4553 gold badges32 silver badges51 bronze badges 2 |2 Answers
Reset to default 2This 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
There is a issue on your work. Hooks are not conditionally called or placed inside loops. While your useState is outside the loop, ESlint works well. As for froEach, this method is a function call and does not affect the execution flow ina way that could confuse ESlint. Howeverm for loops have different behavior in terms of scoping and hoisting , and it is risk on ESlint rule.
So you can use forEach or map instead of for.
Array.from({ length }).forEach((_, i) => {})
, or better yet, wrapping the loop in auseEffect
oruseMemo
works better for you – DustInComp Commented Jan 31 at 13:45