useEffect is where React beginners bleed. These five mistakes cover most of the pain.
1. The infinite loop
// โ setState โ re-render โ effect runs โ setState โ ...
useEffect(() => {
setData(compute(data));
}); // no dependency array!
// โ
add the array
useEffect(() => { ... }, []);2. Objects in the dependency array
[{...}] is a NEW object every render โ effect fires every render. Depend on primitive fields ([user.id]) instead of objects ([user]).
3. No cleanup
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id); // โ without this: leaks + double timers
}, []);4. Race conditions in fetches
Type fast in a search box โ responses return out of order โ stale data wins. Fix with a cancelled flag in cleanup or AbortController.
5. Using useEffect at all
Deriving state from props? Compute it during render. Responding to a click? Put it in the handler. Effects are for synchronizing with external systems only โ the most senior insight of the list.
More: React interview questions Q16โ30.
โ All Articles