What is Lightning Message Service (LMS) and how do you use it to communicate between components?
Answer
LMS lets components on the same Lightning page communicate regardless of DOM hierarchy, and works across LWC, Aura and Visualforce.
Steps:
- Create a Lightning Message Channel metadata file (
MyChannel.messageChannel-meta.xml) defining fields. - Publisher imports the channel and
publish:
javascript
import { publish, MessageContext } from 'lightning/messageService';
import CHANNEL from '@salesforce/messageChannel/MyChannel__c';
@wire(MessageContext) messageContext;
publish(this.messageContext, CHANNEL, { recordId: this.id });
- Subscriber uses
subscribeinconnectedCallbackandunsubscribeindisconnectedCallback.
It replaces the old pub-sub pattern and is the supported way to talk between unrelated components.
lwclmsmessaging