Memory Allocation Discipline Example Async

1 min read
Rapid overview

Memory Allocation Example (Async)

This example shows how async flows can leak memory when subscriptions aren't cleaned up.


Problem

A component subscribes to events but never unsubscribes.

const onResize = () => console.log('resize');
window.addEventListener('resize', onResize);

Fix

Unsubscribe on cleanup.

const onResize = () => console.log('resize');
window.addEventListener('resize', onResize);

return () => window.removeEventListener('resize', onResize);

Takeaway

Always clean up subscriptions or listeners in async flows to avoid retained references.