Earlier when we had to send data from one component to another component that is not within the hierarchy then we were relying upon PubSub.
It's a library that Salesforce provided that's dependent on Publish and Subscribe model.
But that approach is a bit roundabout and tedious for developers to use.
So Salesforce came up with Lightning Message Service which is used to send data from one LWC Component to another LWC Component. Also, it's used for communication between LWC, Aura, and Visualforce pages too.
Let's look at how to send data using Lightning Message Service in LWC.
The first thing that we need to create is a Message Channel. We cannot create a Message Channel (via an XML file) from the Salesforce Developer Org or Sandbox. We need to create it from VS Code and push it to the respective org.
Here is the XML file used to create a MessageChannel.
Create an XML file with the extension .messageChannel-meta.xml
This is the template file that transmits the data on click of the button.
This is the JavaScript file of the Web Lightning Web Component.
This is a template that is going to receive the data that the other component publishes using the Message Channel.
We will only be receiving the data when we subscribe.
This is the JavaScript controller of the Web Component that subscribes to the Message Channel (on click of the button on the template file).