Defensive Programming Against Leaks
You'll learn how to proactively prevent memory leaks by establishing cleanup patterns, using AbortController, and managing component lifecycles.
The Core Idea
Defensive programming against leaks means writing code that assumes cleanup will be necessary and builds it in from the start, rather than fixing leaks reactively. It's like always putting away tools as you finish with them, rather than letting your workshop get cluttered and cleaning once a year.
Essential Defensive Patterns
Always Plan for Cleanup
Whenever you set up a listener, timer, or subscription, immediately write the corresponding cleanup code:
function setupComponent() {
const timer = setInterval(update, 1000);
window.addEventListener('resize', handleResize);
// Cleanup function created at same time as setup
return function cleanup() {
clearInterval(timer);
window.removeEventListener('resize', handleResize);
};
}
const cleanup = setupComponent();
// Later: cleanup();
AbortController for Centralized Cancellation
Use AbortController to cancel multiple operations at once:
const controller = new AbortController();
const { signal } = controller;
fetch('/api/data', { signal });
element.addEventListener('click', handler, { signal });
setTimeout(() => console.log('tick'), 5000, { signal }); // Not standard but illustrative
// One line cancels everything
controller.abort();
Lifecycle Thinking
Structure your code with clear setup/teardown phases, even in plain JavaScript:
class Component {
mount() {
this._cleanup = [];
this._cleanup.push(this.setupTimer());
this._cleanup.push(this.setupListeners());
}
unmount() {
this._cleanup.forEach(fn => fn());
this._cleanup = [];
}
}
Key Takeaway: Write cleanup code at the same moment you write setup code, use AbortController for unified cancellation, and always think in terms of component lifecycles—even a simple function can have "start" and "end" phases that need managing.