# What is the Lightning Message Service (LMS), and when should you use it for cross-component communication?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, LMS, Cross-Component Communication

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-the-lightning-message-service-lms-and-when-should-you-use-it-for-cross-component-communication

## Answer

**Basics:** When two components are siblings, unrelated, or built with different frameworks, events and properties cannot connect them. LMS gives them a shared named channel: one publishes a message, any subscriber on the page receives it. Typical examples: a filter panel updating a results list, or a selector driving a detail view.

**How it works:**
1. Create `force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xml` with `isExposed` true and the field names allowed in the payload.
2. In LWC, import the channel (`@salesforce/messageChannel/RecordSelected__c`) plus `publish`, `subscribe`, `unsubscribe`, `MessageContext`, `APPLICATION_SCOPE` from `lightning/messageService`.
3. Get context with `@wire(MessageContext) messageContext;`.
4. Publisher: `publish(this.messageContext, CHANNEL, { recordId })`.
5. Subscriber: in `connectedCallback` call `subscribe(this.messageContext, CHANNEL, msg => ..., { scope: APPLICATION_SCOPE })`; in `disconnectedCallback` call `unsubscribe`.
6. Aura uses `lightning:messageChannel`; Visualforce uses `sforce.one` style `$MessageChannel` references.

**Advanced / deep dive:** By default a subscriber only receives messages while its component is active (for example the visible tab); `APPLICATION_SCOPE` receives them even when not active. Messages are JSON-serializable; do not send functions or large payloads, send ids and let receivers fetch data. LMS works within one browser tab or window; it cannot talk across tabs or windows, and it is not for server push, where `lightning/empApi` and platform events apply. Experience Cloud support depends on the site type and framework, so verify in current release notes. Compared with a pub/sub JavaScript module, LMS is supported, crosses framework boundaries and respects Lightning page lifecycle. Compared with bubbling events it avoids tight coupling, but it creates implicit global dependencies, so name channels by business concept and document payloads. Container-based communication (events and `@api`) remains better when a parent-child relationship exists.

**Code / config example:**
```xml
<!-- RecordSelected.messageChannel-meta.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>RecordSelected</masterLabel>
    <isExposed>true</isExposed>
    <description>Fired when a record is selected</description>
    <lightningMessageFields>
        <fieldName>recordId</fieldName><description>Selected Id</description>
    </lightningMessageFields>
</LightningMessageChannel>
```
```javascript
import { LightningElement, wire } from 'lwc';
import { publish, subscribe, unsubscribe, MessageContext, APPLICATION_SCOPE } from 'lightning/messageService';
import CHANNEL from '@salesforce/messageChannel/RecordSelected__c';

export default class Picker extends LightningElement {
    @wire(MessageContext) messageContext;
    sub;
    connectedCallback() {
        this.sub = subscribe(this.messageContext, CHANNEL,
            m => { this.selected = m.recordId; }, { scope: APPLICATION_SCOPE });
    }
    disconnectedCallback() { unsubscribe(this.sub); this.sub = null; }
    select(id) { publish(this.messageContext, CHANNEL, { recordId: id }); }
}
```

**Hidden gotchas & must-remember points:**
- The import path uses the `__c` suffix, even though you named the file without it.
- Always unsubscribe in `disconnectedCallback` to prevent leaks and duplicate handlers.
- Without `APPLICATION_SCOPE`, inactive tabs and utility items miss messages.
- Messages do not cross browser tabs or reach non-Lightning contexts.
- Payload fields not declared in the channel may be dropped; keep payloads small.
- LMS is not a persistence or server-event mechanism.

**Best practice:** Use LMS only for decoupled communication, with small id-based payloads and disciplined subscribe and unsubscribe.

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