Component Communication · Lesson 10 of 25
Lightning Message Service (LMS) in LWC
Events work between a parent and its children. But many components on a Lightning page aren't related at all: a filter panel in the left column and a chart in the main region, or an account list and a map. Lightning Message Service (LMS) lets them talk through a named message channel: one component publishes, any number subscribe – even across LWC, Aura and Visualforce on the same page.
In this lesson
- Creating a message channel
- Publishing a message
- Subscribing and unsubscribing
- Scope and when to use LMS
One channel, many components
- RegionSelected__c (message channel)
- regionFilter – publishes { region }
- salesChart – subscribes, reloads its data
- topAccounts – subscribes, filters its list
1. Create the message channel
A channel is metadata in force-app/main/default/messageChannels/, deployed like any other:
<?xml version="1.0" encoding="UTF-8"?>
<!-- RegionSelected.messageChannel-meta.xml -->
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>RegionSelected</masterLabel>
<isExposed>true</isExposed>
<description>Sent when the user picks a sales region.</description>
<lightningMessageFields>
<fieldName>region</fieldName>
<description>The selected region name</description>
</lightningMessageFields>
</LightningMessageChannel>
Components import it as @salesforce/messageChannel/RegionSelected__c – the file name plus __c.
2. Publish
<!-- regionFilter.html -->
<template>
<lightning-combobox label="Region" value={region} options={options} onchange={handleChange}></lightning-combobox>
</template>
// regionFilter.js
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import REGION_SELECTED from '@salesforce/messageChannel/RegionSelected__c';
export default class RegionFilter extends LightningElement {
region = 'APAC';
options = ['APAC', 'EMEA', 'Americas'].map((r) => ({ label: r, value: r }));
@wire(MessageContext) messageContext; // required for publish and subscribe
handleChange(event) {
this.region = event.detail.value;
publish(this.messageContext, REGION_SELECTED, { region: this.region });
}
}
Region [APAC ▾]
› choose “EMEA” in Region
Region [EMEA ▾]
publish on RegionSelected__c: {"region":"EMEA"}
› choose “Americas” in Region
Region [Americas ▾]
publish on RegionSelected__c: {"region":"Americas"}3. Subscribe
<!-- salesChart.html -->
<template>
<lightning-card title="Sales by region">
<p>Showing: {region}</p>
<p>Revenue: {revenue}</p>
</lightning-card>
</template>
// salesChart.js
import { LightningElement, wire } from 'lwc';
import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService';
import REGION_SELECTED from '@salesforce/messageChannel/RegionSelected__c';
const REVENUE = { APAC: '$1.2M', EMEA: '$2.4M', Americas: '$3.1M' };
export default class SalesChart extends LightningElement {
region = 'All regions';
subscription = null;
@wire(MessageContext) messageContext;
get revenue() {
return REVENUE[this.region] ?? '$6.7M';
}
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(this.messageContext, REGION_SELECTED, (message) => this.handleMessage(message));
}
}
disconnectedCallback() {
unsubscribe(this.subscription); // always clean up
this.subscription = null;
}
handleMessage(message) {
this.region = message.region;
}
}
▌Sales by region
Showing: All regions
Revenue: $6.7M
subscribed to RegionSelected__c
› another component publishes {"region":"EMEA"}
▌Sales by region
Showing: EMEA
Revenue: $2.4M
› another component publishes {"region":"APAC"}
▌Sales by region
Showing: APAC
Revenue: $1.2M
› component removed from the page
unsubscribed@wire(MessageContext)gives the component its messaging context; pass it topublishandsubscribe.- Subscribe in
connectedCallbackand unsubscribe indisconnectedCallback, so a removed component doesn't keep receiving messages. - The message is a plain object; keep it small – send Ids and choices, not whole records.
Scope
By default, a subscriber only receives messages while it's in an active area of the app – a component in a background workspace tab doesn't. To receive messages everywhere in the app, subscribe with application scope:
import { subscribe, APPLICATION_SCOPE, MessageContext } from 'lightning/messageService';
this.subscription = subscribe(this.messageContext, REGION_SELECTED, (m) => this.handleMessage(m), { scope: APPLICATION_SCOPE });
When to use what
| Relationship | Use |
|---|---|
| Parent → child | @api properties and methods |
| Child → parent | custom events |
| Unrelated components on a page, or LWC ↔ Aura ↔ Visualforce | Lightning Message Service |
| Sharing the same record data | Lightning Data Service – it keeps components in sync automatically |
Avoid the old pubsub module
Older projects copied a pubsub helper from Salesforce sample apps. It only works within one page and isn't supported in all containers. LMS is the supported replacement.
Practice
Try it yourself
Write a
caseCounterthat subscribes toCaseClosed__cand counts messages: "Cases closed this session: N".Show solution
<!-- caseCounter.html --> <template> <p>Cases closed this session: {count}</p> </template>// caseCounter.js import { LightningElement, wire } from 'lwc'; import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService'; import CASE_CLOSED from '@salesforce/messageChannel/CaseClosed__c'; export default class CaseCounter extends LightningElement { count = 0; subscription; @wire(MessageContext) messageContext; connectedCallback() { this.subscription = subscribe(this.messageContext, CASE_CLOSED, () => { this.count++; }); } disconnectedCallback() { unsubscribe(this.subscription); } }Cases closed this session: 0 subscribed to CaseClosed__c › another component publishes {"caseId":"500A"} Cases closed this session: 1 › another component publishes {"caseId":"500B"} Cases closed this session: 2
Quick check
What do publish and subscribe both need?
The MessageContext (from @wire) and the imported message channel.
Why unsubscribe in disconnectedCallback?
So a removed component stops receiving messages and doesn't leak memory.
How do you receive messages from inactive tabs too?
Subscribe with { scope: APPLICATION_SCOPE }.
Summary
- LMS connects unrelated components through a message channel metadata file.
- publish(context, channel, message); subscribe in connectedCallback and unsubscribe in disconnectedCallback.
- Choose @api, events, LMS or Lightning Data Service by how components relate.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.