Cleanup Functions in useEffect
Cleanup Functions in useEffect
1. Why Cleanup Is Essential
Not all side effects are "fire-and-forget". Many side effects establish connections, timers, or event listeners that will cause serious memory leaks, duplicated callbacks, or state updates on unmounted components if not properly disassembled when the component disappears:
- Timers:
setInterval,setTimeout - Subscriptions: WebSockets, Firebase real-time listeners, Chat services
- DOM Event Listeners:
window.addEventListener('resize', ...) - Abortable Fetch Requests:
AbortController
To clean up after side effects, return a cleanup function from your useEffect callback.
2. Example: Window Resize Listener
3. Example: Timer with setInterval
If you omit clearInterval(timerId), the timer will keep running in the background forever—even after the user navigates to a completely different page—leaking memory and triggering phantom state updates.
4. Canceling Network Requests with AbortController
If a user rapidly toggles between different tabs or pages, an earlier API request might finish after the component has already unmounted. Use standard browser AbortController to cancel in-flight requests:
Practice Quiz
useEffect?setInterval timer is created in useEffect without a cleanup function?fetch requests inside a useEffect cleanup function?<React.StrictMode> run effect setup and cleanup twice during development?Inline Styles and Style Objects
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| The Dependency Array and Execution Lifecycle | Inline Styles and Style Objects |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.