๐งน Cleanup in useEffect()
In React, cleanup functions inside useEffect()
help prevent memory leaks by removing subscriptions, timers, or listeners when a component unmounts or re-renders.
โ Why Cleanup Is Important
- Prevents memory leaks in long-running applications
- Clears timers, intervals, and subscriptions
- Avoids unwanted behavior like duplicated event listeners
๐ Example: setInterval Cleanup
import React, { useState, useEffect } from "react";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(prev => prev + 1);
}, 1000);
return () => {
clearInterval(timer); // ๐ Clean up the interval
};
}, []);
return <p>Seconds: {count}</p>;
}
Without cleanup, the interval would continue even after the component is removed from the DOM.
๐ฑ๏ธ Example: Event Listener Cleanup
useEffect(() => {
function handleResize() {
console.log("Window resized");
}
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize); // โ Prevent multiple listeners
};
}, []);
Always clean up event listeners to avoid multiple identical callbacks running.
๐ When Does Cleanup Run?
- When the component unmounts (like navigating away)
- Before running a new effect (if dependencies change)
โ Summary
- Return a function inside
useEffect()
to handle cleanup - Useful for intervals, subscriptions, event listeners
- Improves performance and stability of your app