Sub topic 8
Managing subscriptions: connectedCallback and disconnectedCallback
This chapter assumes you can write a basic Lightning web component and know the lifecycle hooks connectedCallback and disconnectedCallback. It also assumes you have already seen subscribe, unsubscribe, and @wire(MessageContext) in the previous chapters. Here you will learn where a subscription belongs in a component's life, what goes wrong when you manage it badly, and how to keep it correct when a component is added, removed, or moved.
Why subscriptions need management
A call to subscribe registers your handler function with Lightning Message Service (LMS). LMS keeps that registration until something removes it. The registration does not end when your component stops being useful. It ends only when you call unsubscribe, or when the page that holds the registration goes away.
A component can leave the page in many ways. A parent can stop rendering it with lwc:if. A user can close a tab in a console app. A Lightning page can navigate away. If the component was removed but still subscribed, LMS would keep calling a handler that belongs to a component nobody sees. That handler stays in memory, along with everything it references through this. It may also try to update state that no longer matters.
So every subscription has a lifetime. The rule is simple: tie the subscription's lifetime to the component's time in the DOM.
The lifecycle pairing
LWC gives you two hooks that match that lifetime:
connectedCallbackruns when the component is inserted into the DOM.disconnectedCallbackruns when the component is removed from the DOM.
Subscribe in the first, unsubscribe in the second. The pair is symmetrical, which makes it easy to review. Every subscribe call should have a matching unsubscribe in the other hook.
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() {
this.subscribeToChannel();
}
disconnectedCallback() {
this.unsubscribeFromChannel();
}
subscribeToChannel() {
if (this.subscription) {
return;
}
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
unsubscribeFromChannel() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
this.selectedId = message.recordId;
}
}Three details in this code matter.
- The subscription object returned by
subscribeis stored in a field. Without it you cannot callunsubscribelater, becauseunsubscribetakes that object and not the channel or the handler. - The handler is an arrow function,
(message) => this.handleMessage(message). A plain method reference would lose itsthisbinding when LMS calls it, andthis.selectedIdwould fail. - The field is set back to
nullafter unsubscribing. That lets the guard insubscribeToChannelwork correctly if the component is connected again.
The lifecycle as a state machine
A component can be connected and disconnected more than once. Moving an element in the DOM, or toggling it with a conditional directive, triggers disconnectedCallback and then connectedCallback again on the same instance in some cases, or creates a fresh instance in others. Your code must work for both.
The diagram shows one consequence you should plan for. LMS does not store messages. If a publisher sends a message while your component is in the Unsubscribed state, the message is gone. When the component reconnects, it starts with no knowledge of what it missed. If your design needs the latest value, the component needs another source for the initial state, such as a wire adapter, an Apex call, or a shared module that holds state.
Why guard against double subscription
The if (this.subscription) check in the example looks defensive, but it prevents a real bug. If connectedCallback runs twice on one instance without a disconnectedCallback between, each call to subscribe would register a new handler. Then every message would run your handler twice. Duplicate handlers cause confusing symptoms: counters that jump by two, server calls made twice, or toast messages that appear in pairs.
The guard costs one line and makes the subscribe step safe to call again. This is also why a separate subscribeToChannel method is useful. You can call it from a button handler or another method without worrying about the current state.
Subscribing on demand
Not every component should subscribe on connect. Some listen only while a feature is turned on. In that case the same helper methods serve both the lifecycle hooks and user actions.
<template>
<lightning-card title="Selection monitor">
<div class="slds-var-p-around_medium">
<lightning-button
label="Start listening"
onclick={handleStart}
disabled={isListening}
></lightning-button>
<lightning-button
label="Stop listening"
onclick={handleStop}
disabled={isStopped}
></lightning-button>
<p>Last selected: {selectedId}</p>
</div>
</lightning-card>
</template>import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class SelectionMonitor extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
get isListening() {
return this.subscription !== null;
}
get isStopped() {
return this.subscription === null;
}
handleStart() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.selectedId = message.recordId;
}
);
}
}
handleStop() {
unsubscribe(this.subscription);
this.subscription = null;
}
disconnectedCallback() {
this.handleStop();
}
}Even with user-controlled subscribing, disconnectedCallback still cleans up. Users forget to press "Stop", and the component must not leak a handler because of that.
The getters read this.subscription, which is a class field. In LWC, all fields are reactive for the purpose of rerendering when their value is reassigned, so the buttons update after each start or stop.
What the default scope does to the lifetime
Subscribing is not the only thing that controls delivery. Scope decides which messages a live subscription receives. With the default scope, your component receives messages only while it is in the active area of the page, such as the active tab or the current navigation item. With APPLICATION_SCOPE, it receives messages from anywhere in the application, even when it sits in a background tab.
The two settings interact with lifecycle in a way that surprises people. A component in a background tab is often still connected. Its connectedCallback has run, and its subscription is alive. Under default scope it simply gets no messages until its area becomes active. Under APPLICATION_SCOPE it processes every message while hidden. If the handler does expensive work, such as a server call, a hidden component pays that cost for no visible benefit.
Choose the scope deliberately, and keep handlers cheap.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Handler runs twice per message | `subscribe` called again without a guard, or two instances of the component are on the page | Check `this.subscription` before subscribing, and confirm how many instances exist |
| Handler runs after the component was removed | No `unsubscribe` in `disconnectedCallback` | Add the cleanup hook and clear the stored subscription |
| `this` is undefined inside the handler | A method was passed as the callback without binding | Pass an arrow function that calls the method |
| `unsubscribe` has no effect | The subscription object was not stored, or a different object was passed | Store the return value of `subscribe` in a field and pass that field |
| Component misses a message sent before it loaded | LMS does not replay messages | Load the initial state from another source |
| Component gets nothing while in a background tab | Default scope limits delivery to the active area | Use `APPLICATION_SCOPE` if background delivery is intended |
Subscribing in connectedCallback and the MessageContext
You may wonder whether this.messageContext is ready inside connectedCallback. The MessageContext wire adapter provides its value to the component before it connects, so the context is available when you subscribe there. This is the pattern the standard LMS documentation uses. If you ever find the value undefined in your own testing, check that the wire is declared on the same class and that the import is MessageContext from lightning/messageService.
A review checklist
Use this list when you read your own code or someone else's.
- Does every
subscribehave a reachableunsubscribe? - Is the return value stored in a field?
- Is the field cleared after unsubscribing?
- Does the subscribe path guard against duplicate registration?
- Is the handler an arrow function or a bound function?
- Is the scope chosen on purpose, and is the handler cheap enough for that scope?
- Does the component recover its state if it misses messages while disconnected?
Exercise
A parent component shows a child with lwc:if={showDetail}. The child subscribes in connectedCallback but has no disconnectedCallback. A user toggles showDetail off and on five times, then a message is published. How many times can the child's handler logic run, and why?
Show answer
Up to five times, or more precisely once per leaked subscription. Each time the child is created and connected it registers a new handler, and nothing removes the old ones when it is removed. Adding a disconnectedCallback that calls unsubscribe on the stored subscription and clears the field makes the handler run once, because only the live instance is subscribed.
Exercise
A component stores its subscription in a field but never sets the field back to null after calling unsubscribe. It is later reconnected, and connectedCallback uses the guard if (!this.subscription). What happens, and how do you fix it?
Show answer
The guard sees the old, non-null object and skips subscribe, so the reconnected component never receives messages. The fix is to set this.subscription = null right after calling unsubscribe.