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:
Three Dependency Patterns
Each pattern has a specific use case:
Cleanup Functions
Effects can return a cleanup function that runs before the next effect or unmount:
Why Cleanup Matters
Without cleanup, you can cause memory leaks and bugs:
Cleanup with Event Listeners
A common pattern for DOM event listeners:
Dependency Comparison
React uses Object.is for comparing dependencies:
Exercise: Dependency Array
Exercise: Timer Cleanup
Exercise: Event Listener Manager
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
Up next ยท Lesson 25 of 33
Common useEffect Patterns
8 min read
24 of 33 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

