Kar

Kar started this conversation 3 months ago.

Infinite re-render loop caused by useEffect dependency on arrays or objects

I have: jsx Copy code const tasks = []; useEffect(() => { fetchTasks().then(setTasks); }, [tasks]); This causes continuous fetching and rendering—even when tasks appear unchanged. Why?

Digiaru

Posted 3 months ago

React shallowly compares dependencies by reference—not content—meaning new arrays/objects—even if identical—are considered different. This causes the effect to rerun endlessly ([turn0reddit13], [turn0reddit19], [turn0search3]). Fixes: • Don’t include arrays/objects directly in the dependency array. • If you must, depend on a primitive like tasks.length or a stable ID list. • Better: Control updates explicitly (e.g. use event handlers, reducer state, or React Query) instead of blind effect loops.