I just wrote a StackOverflow post in which I found a workaround for the React ESLint Plugin seemingly erroneously giving an error that useState was being called conditionally when it was actually called after a for loop in top-level code.
As mentioned in the post, rather than moving the useState call before the loop, I needed to use that loop to set the inital value of the state. By using .forEach(), I was able to get rid of the error from ESLint and make the code work, but, as mentioned at the end of my answer
i'm pretty sure that tricking ESLint into not giving an error like this is not a good long-term solution. Ideally ESLint rules probably need updating to better check for improper use of conditionals, and/or the react docs should be updated with an example for how to conditionally set a hook's default value in a way that doesn't violate the rules of react hooks.
Because this solution feels like its a little hacky and not the best long-term solution to this problem, I wanted to get clarification on what would be the correct solution in this case and hopefully get the dosumentation and ESLint plugins updated to reflect this (if necessary)
I just wrote a StackOverflow post in which I found a workaround for the React ESLint Plugin seemingly erroneously giving an error that
useStatewas being called conditionally when it was actually called after a for loop in top-level code.As mentioned in the post, rather than moving the
useStatecall before the loop, I needed to use that loop to set the inital value of the state. By using.forEach(), I was able to get rid of the error from ESLint and make the code work, but, as mentioned at the end of my answerBecause this solution feels like its a little hacky and not the best long-term solution to this problem, I wanted to get clarification on what would be the correct solution in this case and hopefully get the dosumentation and ESLint plugins updated to reflect this (if necessary)