# Why is disconnectedCallback crucial for proper component cleanup and memory leak prevention?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, Lifecycle Hooks, Memory Management

Read it on the site: https://www.forcechallenges.com/interview-questions/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. `empApi` 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.

**Code / config example:**
```javascript
import { LightningElement, wire } from 'lwc';
import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService';
import CHANNEL from '@salesforce/messageChannel/Filters__c';

export default class Listener extends LightningElement {
    @wire(MessageContext) messageContext;
    subscription = null;
    timer;

    connectedCallback() {
        this.subscription = subscribe(this.messageContext, CHANNEL, (m) => this.handle(m));
        this.timer = setInterval(() => this.poll(), 30000);
    }
    disconnectedCallback() {
        unsubscribe(this.subscription);
        this.subscription = null;
        clearInterval(this.timer);
    }
    handle(m) {}
    poll() {}
}
```

**Hidden gotchas & must-remember points:**
- It is not a guaranteed "page is closing" hook; do not rely on it to save data or send requests when the browser tab closes.
- It may fire when a component is merely moved, followed by another `connectedCallback`.
- `removeEventListener` silently does nothing if you pass a different function reference.
- Do not access child components in it; they may already be disconnected.
- Wire adapters clean up automatically; you only handle what you registered manually.
- Leaks show up as duplicate handler calls after repeated navigation.

**Best practice:** For every `add`/`subscribe`/`setInterval` in `connectedCallback`, write the matching cleanup in `disconnectedCallback` in the same commit.

---
Source: ForceChallenges · last updated 2026-11-02
