React’s useEffect() Hook is used for side effects like API calls, timers, and event listeners. One common beginner mistake is creating infinite loops inside useEffect().
Example of wrong code:
useEffect(() => {
setCount(count + 1);
});
This creates an infinite loop because:
- Component renders
-
useEffect()runs - State updates
- Component re-renders
-
useEffect()runs again
This process repeats forever.
The correct way is:
useEffect(() => {
setCount(count + 1);
}, []);
The empty dependency array [] tells React to run the effect only once after the first render.
Dependency array behavior:
- No dependency array → runs after every render
- Empty array
[]→ runs once -
[value]→ runs when value changes
Another common mistake is using objects or functions in dependency arrays because React compares references, not actual values.
Best practices:
- Use dependency arrays correctly
- Avoid unnecessary state updates
- Keep
useEffect()simple - Understand React rendering flow
Understanding useEffect() properly helps developers avoid performance issues and debugging problems in React applications.
Top comments (0)