You think you know React... until you have to clean up a third-party script.
I had a major "Aha!" moment building my Financial dashboard project, and it's a perfect example of how React's declarative world meets imperative, real-world JavaScript.
The Problem: I'm integrating TradingView's embeddable widgets, which aren't React components. This requires manually creating <script> tags and injecting them into a div using a useEffect hook.
The Naive Approach: Just create the script in useEffect and let React unmount the div when it's done. Simple, right?
Wrong. This creates massive memory leaks.
The third-party script (the "tenant") running inside my div (the "house") has its own background processes: setIntervals, WebSockets, and global event listeners. When React unmounts the div (demolishes the house), it doesn't tell the tenant to clean up. The "ghost" tenant lives on, still fetching data and consuming memory.
The Solution & The "Aha!" Moments:
1. The "Stale Ref" Problem: My first attempt at a cleanup function failed because ref.current is null when the cleanup runs!
The Fix: You have to snapshot the ref's value inside the effect: const node = ref.current;. The cleanup function's closure then remembers this node, even after ref.current is nullified.
2. The "Tenant Eviction" Model: This was the real lightbulb moment. Why clean the div with node.innerHTML = "" if React is removing it anyway?
The Fix: The cleanup is not for React. It's a signal for the third-party script. Setting innerHTML = "" is like "evicting the tenant." The script is built to detect this, triggering its own internal destroy() logic—clearing its timers, closing its connections, and actually preventing the memory leak.
Takeaway: React manages its own lifecycle, but we are 100% responsible for the lifecycle of any imperative, non-React code we introduce. This dive was a powerful lesson in JavaScript closures, React's lifecycle, and robust memory management.
#reactjs #javascript #webdevelopment #frontend #MERNstack #reacthooks #memorymanagement #learning #coding
JavaScript keeps reminding us who’s the boss 😂