useEffect Cleanup
Question
When does the cleanup function in useEffect run?
Hint
Cleanup is for subscriptions, timers, listeners.
Explanation
The cleanup function returned from useEffect runs before the next effect execution (when dependencies change) and when the component unmounts. This is essential for preventing memory leaks: clearing timers (clearInterval), removing event listeners, closing subscriptions/WebSockets, aborting fetch requests. The cleanup runs in the order: cleanup previous effect, then run new effect. On unmount, only the final cleanup runs.
Related Resources
Related Lessons
- useEffect
Learn useEffect.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.