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
التالي · الدرس 25 من 33
Common useEffect Patterns
قراءة 8 دقيقة
أنهيت 24 من 33 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

