Skip to content

Cleanup patterns

const id = setInterval(fn, 1000);
clearInterval(id);

Framework: return cleanup from useEffect, onUnmounted, destroy().

const ctrl = new AbortController();
el.addEventListener('click', onClick, { signal: ctrl.signal });
// later:
ctrl.abort();
const observer = new MutationObserver(callback);
observer.observe(target, options);
observer.disconnect();
process.on('SIGTERM', async () => {
server.close();
await pool.end();
clearInterval(metricsInterval);
});
flowchart LR
  mount[Component mount] --> attach[Attach listeners timers]
  attach --> unmount[Component unmount]
  unmount --> cleanup[Cleanup all handles]
  • Every setInterval has owner + clearInterval
  • Every addEventListener has removal path
  • Every fetch has AbortController on unmount
  • Every open stream/socket has close/destroy