React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
How to prevent infinite loops with useEffect?
Infinite loops happen when the effect updates state that’s listed in its own dependency array, which causes the effect to re-run, updating state again and so on.
Infinite loop scenario:
js
useEffect(() => {
setCount(count + 1);
}, [count]); // Triggers again every time count updates
You need to ensure that setState calls do not depend on values that cause the effect to rerun, or isolate them with a guard.
js
useEffect(() => {
if (count < 5) {
setCount(count + 1);
}
}, [count]);