When using useEffect, sometimes you need to clean up resources like timers, subscriptions, or event listeners.
📘 Example:
import { useEffect } from "react";
function Timer() {
useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => clearInterval(timer); // cleanup
}, []);
}
✨ Key Points:
• Cleanup prevents memory leaks
• Runs when the component unmounts
• Also runs before the effect executes again
Always clean up side effects to keep your React apps efficient and bug-free. 🚀
Top comments (0)