useEffect Dependencies and Cleanup
The dependency array controls when your effect runs, and cleanup functions prevent memory leaks. Understanding these concepts is crucial for writing correct effects.
The Dependency Array
The second argument to useEffect determines when the effect should re-run:
Loading React playground...
Three Dependency Patterns
Each pattern has a specific use case:
Loading React playground...
Cleanup Functions
Effects can return a cleanup function that runs before the next effect or unmount:
Loading React playground...
Why Cleanup Matters
Without cleanup, you can cause memory leaks and bugs:
Loading React playground...
Cleanup with Event Listeners
A common pattern for DOM event listeners:
Loading React playground...
Dependency Comparison
React uses Object.is for comparing dependencies:
Loading React playground...
Exercise: Dependency Array
Loading exercise...
Exercise: Timer Cleanup
Loading exercise...
Exercise: Event Listener Manager
Loading exercise...
Key Takeaways
- No deps - Effect runs after every render
- Empty deps [] - Effect runs only once on mount
- With deps [a, b] - Effect runs when any dependency changes
- Cleanup function - Return a function to clean up before next effect or unmount
- Reference comparison - Objects and arrays need stable references to avoid running every time

