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)