FrontendDeveloper.in

React question detail

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:

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.

useEffect(() => {
if (count < 5) {
setCount(count + 1);
}
}, [count]);
Back to all React questions
Get LinkedIn Premium at Rs 399