Sub topic 12
When to use LMS and when to use something else
This chapter assumes you can publish and subscribe with lightning/messageService, and that you know the channel, MessageContext, scope and unsubscribe material from earlier chapters. You should also know how @api properties and CustomEvent work in LWC. The goal here is to decide whether LMS is the right tool for a given problem. LMS is easy to reach for, but it is often more than you need and sometimes not enough.
What LMS is good at
LMS is a publish/subscribe bus for the current page. Its strengths follow from that design:
- No shared parent is required. Publisher and subscriber can sit in different regions of a Lightning page.
- It crosses frameworks. LWC, Aura and Visualforce can all use the same channel in Lightning Experience.
- The contract is metadata. The channel is a deployable
LightningMessageChannelfile, so teams can agree on it without sharing code. - Coupling is loose. The publisher does not know who listens, and a subscriber can be removed without touching the publisher.
Its limits matter just as much when you choose a pattern:
- Messages live only in the browser page. They are not stored, so a component that subscribes late never sees earlier messages.
- No reply. A publisher cannot get a return value or confirmation from a subscriber.
- No delivery across users or tabs. A message reaches only subscribers on the same page, in the same browser session.
- Lightning Experience only. Do not plan on it for Salesforce Classic.
- Payloads must be serializable. Pass plain data, not functions or component references.
The alternatives
Public properties and methods
If one component renders the other, use @api properties to pass data down and @api methods for commands. This is the simplest option, and it is easy to trace in code and in tests. LMS adds nothing here except indirection.
Custom events
For child-to-parent communication, dispatch a CustomEvent. The parent listens with onselect or a similar handler in its template. Events can also pass through several levels of nesting:
this.dispatchEvent(
new CustomEvent('select', {
detail: { recordId: this.recordId },
bubbles: true,
composed: true
})
);With bubbles: true and composed: true, the event travels up through shadow boundaries to any ancestor that listens. Use this sparingly. Broad events leak into parts of the DOM you did not intend, and any ancestor can intercept them. If the receiver is an ancestor, an event is almost always better than LMS. If the receiver is a sibling in a different part of the page, an event cannot reach it.
Lightning Data Service
Many "sharing" problems are really about sharing record data. If two components both read the same record with getRecord or a record form, Lightning Data Service caches it and updates both when the record changes. You do not need a message to keep them in sync.
The usual split is this. LMS carries the identity of the thing ("record 001... was selected"). Lightning Data Service carries the data about it. The subscriber below receives only an Id and loads the fields itself:
import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountName extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
@wire(getRecord, { recordId: '$selectedId', fields: [NAME_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.selectedId = message.recordId;
},
{ scope: APPLICATION_SCOPE }
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
}The $selectedId reference makes the wire reactive. It does not fire until selectedId has a value, and it re-runs whenever a new message arrives.
The pubsub module
Older code samples use a pubsub helper module copied from the Lightning Web Components recipes. It works only between LWCs on the same page. It cannot reach Aura or Visualforce, and it is a copy of sample code, not a supported platform service. For new work, prefer LMS. If a project still uses pubsub, migrating to LMS is mostly a matter of creating a channel and replacing the register and fire calls with subscribe and publish.
A shared JavaScript module
Because ES modules are singletons within a page, two LWCs that import the same module share its state. You can export a small store with a list of listeners and use it as a bus. This works, and it has no metadata to deploy. The costs are:
- It covers only LWC. Aura and Visualforce cannot import it.
- It has no standard lifecycle or scope handling, so you must write your own unsubscribe logic.
- It makes the contract implicit in code, so components in different packages can drift apart.
It is reasonable for tightly related components in one package. It is a poor choice as a general integration point.
Platform events and Streaming API
If the trigger comes from the server, or must reach other users, LMS is the wrong layer. A Platform Event published from Apex, a trigger or a flow can be received in a component with lightning/empApi. This pattern reaches every logged-in user who is subscribed, not just the current page. It needs a network round trip and counts against platform event limits, so do not use it for in-page UI coordination.
A component can bridge the two. It receives the platform event through empApi and republishes a smaller message on an LMS channel for the other components on the page.
Apex and `refreshApex`
If a component changes server data and others must show the new data, a message is not always needed. Call refreshApex on the wired result, or notify Lightning Data Service with notifyRecordUpdateAvailable. This keeps the server as the source of truth instead of passing state between components.
Page state and navigation
If the shared state should survive a reload, be bookmarkable, or work with the browser back button, put it in the URL. CurrentPageReference gives components the page state parameters, and NavigationMixin updates them. LMS state vanishes when the page reloads.
Comparison
| Pattern | Reaches | Crosses LWC/Aura/VF | Keeps state | Best for |
|---|---|---|---|---|
| `@api` property or method | Direct child | No | In the component | Parent configuring a child |
| `CustomEvent` | Parent or ancestors | No | No | Child reporting to a parent |
| Lightning Data Service | Any component using the record | Yes for LWC and Aura | Cached record data | Sharing record fields |
| `pubsub` sample module | LWCs on one page | No | No | Legacy code only |
| Shared JS module | LWCs that import it | No | Yes, in memory | Related components in one package |
| LMS | Any subscriber on the page | Yes | No | Unrelated components on one page |
| Platform event with `empApi` | Any subscribed user | LWC and Aura | Event replay window | Server-driven or cross-user updates |
| URL page state | Anything reading the URL | Yes | In the URL | Bookmarkable, reload-safe state |
A decision path
Start with the cheapest pattern that works and move down only when it fails.
Failure modes of choosing LMS too early
- Hidden dependencies. A channel has no compile-time link to its subscribers. When a team renames a field in the payload, nothing fails at build time. You find out when a subscriber shows
undefined. - Message ordering and timing. A subscriber that connects after the publish call never gets the message. If the subscriber might render later (a tab, a conditional
if:trueblock), store the state elsewhere, or have the subscriber ask for the current value when it connects. - Leaked subscriptions. A missing
unsubscribeindisconnectedCallbackleaves handlers that run on detached components. See the lifecycle chapter for the pattern. - Event storms. Publishing on every keystroke or mouse move floods subscribers. Debounce on the publisher side or publish only on commit actions.
- Replacing data access. Sending whole records through a channel duplicates Lightning Data Service and goes stale. Send identifiers and let subscribers fetch.
Practical criteria
Choose LMS when most of these are true:
- The components are on the same Lightning Experience page and have no common owner in the component tree.
- At least one of them is Aura or Visualforce, or they come from different packages or teams.
- The signal is a transient notification, such as "selection changed", "filter applied" or "item added".
- Late subscribers do not need to see past messages.
- The payload is a few primitive fields or identifiers.
Choose something else when any of these is true:
- The relationship is parent and child.
- The data is a record that Lightning Data Service already manages.
- The signal originates on the server or must reach other users.
- The state must survive navigation or be shareable as a link.
- The receiver needs to respond to the sender.
Exercise
A page has a product list on the left and a "recently viewed" panel on the right. Both are LWCs placed on the Lightning page by an admin. When a user clicks a product, the panel must add it to its list. The panel is hidden on a collapsed tab until the user opens it. What pattern fits, and what must you add to handle the hidden tab?
Show answer
LMS fits, because the two components share no parent and are only related by being on the same page. Publish the product Id on a channel when the user clicks. Messages are not stored, so a panel that has not yet connected on the collapsed tab would miss them. Keep the viewed list in a place the panel can read at load time, such as a shared store, an Apex-backed record or page state. The panel reads it in connectedCallback and then updates from new messages.
Exercise
Your teammate wants a component to show a banner when a background Apex job finishes, for every user who is logged in. They propose an LMS channel. Is that the right choice? What would you use instead?
Show answer
No. LMS messages exist only in the browser page where they are published, so they cannot reach other users or react to a server-side job. Publish a Platform Event from the Apex job and subscribe to it with lightning/empApi in the banner component. If other components on the page also need to react, the banner component can republish a small LMS message after it receives the event.