Why is disconnectedCallback crucial for proper component cleanup and memory leak prevention?
Answer
Basics: JavaScript garbage collection only frees an object when nothing references it. A component that adds a listener to window, starts a setInterval, or subscribes to a message channel is referenced by those registries even after the user navigates away. That is a memory leak, and the stale handler may keep running against a dead component (extra Apex calls, errors, duplicate toasts). disconnectedCallback is the symmetrical cleanup hook.
How it works: When the host is removed (navigation, lwc:if going false, parent re-render removing it) the engine calls disconnectedCallback. Typical cleanup: removeEventListener with the same function reference, clearTimeout/clearInterval, unsubscribe(this.subscription) for Lightning Message Service (lightning/messageService), unsubscribe for lightning/empApi, disconnecting ResizeObserver/IntersectionObserver/MutationObserver, and aborting pending work with a flag.
Advanced / deep dive: Because moving an element triggers disconnect then connect, symmetric setup and teardown keeps behavior correct. Listeners must be removed using the same reference, so store arrow functions as class fields rather than inlining them. Pending promises cannot be cancelled; guard their continuation with a _disconnected flag so a late response does not set state on a removed component. Lightning Message Service subscriptions created with subscribe(..., { scope: APPLICATION_SCOPE }) live across the app and must be explicitly unsubscribed; subscriptions without that scope are tied to the active component, but explicit unsubscribe is still the safe habit. subscriptions also count against streaming client limits, so leaking them has real cost. In Lightning Experience, console apps and tabs may keep components alive in the background, so removal might happen later than you expect.