What Is useEffect Cleanup Function?
The cleanup function in useEffect runs when a component unmounts or before re-running the effect.
It’s used to clean up side effects like timers, subscriptions, or event listeners.
Basic Syntax
useEffect(() => {
// side effect logic
return () => {
// cleanup logic
};
}, [dependencies]);
Example: Timer Cleanup
import React, { useState, useEffect } from "react";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(interval); // cleanup
}, []);
return <h2>Count: {count}</h2>;
}
export default Timer;
✅ Cleanup prevents memory leaks when component unmounts.
Key Points
- Cleanup runs before effect re-runs and on unmount
- Prevents memory leaks from timers, subscriptions, or event listeners
- Essential for robust React apps
- Works with any side effect in functional components
Conclusion
The useEffect cleanup function ensures efficient resource management, keeping React apps safe and performant.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP