React Memory Leak: Unmounted Component with useEffect

Your component unmounted. But your timer didn't. This is one of the most common memory leaks in React — and it leaves zero errors in the console. Here's what's happening: 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: useEffect(() => {  const id = setInterval(() => {   console.log('still running...');   setData(fetch()); // setting state on unmounted component  }, 1000); }, []); User navigates away. Component unmounts. But the interval is still alive in memory. Still firing. Still trying to update state that no longer exists. React will warn you: "Can't perform a React state update on an unmounted component" But by then — the leak already happened. 𝗪𝗶𝘁𝗵 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: useEffect(() => {  const id = setInterval(() => {   console.log('running...');  }, 1000);  return () => clearInterval(id); // 👈 this is the cleanup }, []); The function you return from useEffect runs in two situations: → Before the effect runs again (dependency changed) → When the component unmounts Think of it as a paired contract: You start something → you are responsible for stopping it. 𝗧𝗵𝗿𝗲𝗲 𝘁𝗵𝗶𝗻𝗴𝘀 𝘁𝗵𝗮𝘁 𝗮𝗹𝘄𝗮𝘆𝘀 𝗻𝗲𝗲𝗱 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: → setInterval / setTimeout → Event listeners (window.addEventListener) → WebSocket or API subscriptions If you start it in useEffect — you clean it up in the return. No exceptions. Have you ever shipped a memory leak from a missing cleanup? 👇 #ReactJS #JavaScript #WebDevelopment #Frontend #useEffect #LearnInPublic #SoftwareEngineering #TypeScript #Programming

  • diagram

To view or add a comment, sign in

Explore content categories