Sub topic 8
Managing subscriptions: connectedCallback and disconnectedCallback
This chapter assumes you can write a basic Lightning web component and know what connectedCallback and disconnectedCallback do. It also assumes you already have a message channel and a publisher, and have seen @wire(MessageContext). Here the focus is on when to subscribe, when to unsubscribe, and what goes wrong if you skip either step.
Why subscriptions need managing
Calling subscribe registers your handler with the message service. The service keeps that registration until you call unsubscribe or the component is destroyed. A subscription is a live reference to your component. If you create one and never release it, you can get two kinds of bugs:
- Duplicate handlers. If the component is added to the DOM more than once, each connection can add another subscription, so one message triggers the handler several times.
- Work after removal. A handler may keep running for a component the user no longer sees.
The fix is to tie the subscription to the component's lifecycle.
The pattern
Subscribe in connectedCallback, which runs when the component is inserted into the DOM. Unsubscribe in disconnectedCallback, which runs when it is removed. Store the return value of subscribe in a field so you can pass it to unsubscribe later.
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordDetail extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
this.selectedId = message.recordId;
}
}Three details in this code matter.
- The
if (!this.subscription)guard prevents a second subscription ifconnectedCallbackruns again on the same instance. disconnectedCallbacksetssubscriptionback tonull. That lets a later reconnection subscribe cleanly and avoids unsubscribing a stale value twice.- The handler is an arrow function,
(message) => this.handleMessage(message). This keepsthispointing at the component insidehandleMessage.
The lifecycle at a glance
Why not subscribe in the constructor
MessageContext is supplied through @wire. The wire service provides it after the component is created, so it is not reliably available in the constructor. By the time connectedCallback runs, the context is available, which makes it the safe place to subscribe.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Handler runs twice per message | The component is subscribed twice, or two instances are on the page | Add the `if (!this.subscription)` guard and check the page for duplicates |
| Messages keep arriving after the component is gone | No `unsubscribe` call | Unsubscribe in `disconnectedCallback` |
| `this` is undefined in the handler | A plain function was passed as the handler | Use an arrow function or bind the method |
| Nothing is received | Subscribed with a missing `MessageContext`, or the scope does not match | Subscribe in `connectedCallback` and check the scope setting |
Subscribing on demand
Not every component should subscribe on load. A component might start listening only after the user clicks a button. The same rules apply: keep the return value, guard against double subscription, and unsubscribe when the user stops listening or when the component disconnects.
handleStartListening() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => this.handleMessage(message)
);
}
}
handleStopListening() {
unsubscribe(this.subscription);
this.subscription = null;
}Keep disconnectedCallback as well, so a component removed while listening still cleans up.
Summary
- Subscribe in
connectedCallback, and keep the returned subscription. - Guard against subscribing twice.
- Unsubscribe in
disconnectedCallbackand reset the field tonull. - Use arrow functions for handlers so
thisrefers to the component.
Exercise
A component calls subscribe in connectedCallback but has no disconnectedCallback. A user opens and closes a tab containing this component three times. What problem can you expect, and how do you fix it?
Show answer
Subscriptions from removed instances may remain registered, so handlers can keep running for components that are no longer displayed, and the number of active handlers grows. Fix it by storing the return value of subscribe in a field, calling unsubscribe(this.subscription) in disconnectedCallback, and setting the field to null.
Exercise
Why does the sample code check if (!this.subscription) before calling subscribe?
Show answer
It prevents a second subscription on the same component instance if connectedCallback runs again without an unsubscribe in between. Without the guard, each message would run the handler more than once.