・Leaving side-effects like subscriptions, timers, or event listeners uncleared can cause memory leaks and unexpected behaviors.This is especially problematic in components that are frequently mounted and unmounted.
// Anti-pattern
React.useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
}, []);
Always return a cleanup function in useEffect to clean up side-effects when the component unmounts.
// Correct approach
React.useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => clearInterval(timer);
}, []);
Top comments (0)