I have a question about React useEffect dependency arrays
I'm updating state inside useEffect, but it keeps running in an infinite loop. Is it not okay to put that state in the dependency array?
I've searched around, but the explanations are all over the place, so I can't make sense of it T_T Any advice would be appreciated.
3 answers
If you take it out of the dependency array, it won't run for now, but that's not a fix—it's just covering it up lol. Since you're changing that state inside, it keeps re-running, so you need to add a condition or restructure it.
I've wasted 3 hours the exact same way, so try questioning the pattern of calling setState inside useEffect itself. Most of the time, it's either (1) moving something that could be handled in an event handler into an effect, or (2) keeping a value in state that could be computed from other state/props. In the latter case, just compute it as a const during render, and you won't need an effect or dependencies. Only use effects for genuine external system subscriptions (WebSockets, timers, DOM manipulation), and for your mental health, avoid calling setState inside them as much as possible. If you must, be sure to use the setState(prev => ...) form and include an early return condition.
Every blog says either don't put it in the dependency array or take it out, but if you follow that, it blows up even worse later. Don't ignore lint warnings—start by looking at why that state needs to be in the dependencies. Infinite loops tend to have clear causes, so if you log the values to the console, you'll find it quickly. Just removing it isn't the answer.