Sub topic 1
The Problem: Components With No Shared Parent
Two components can sit on the same Lightning page and still have no way to talk to each other. This chapter explains why the standard communication tools in Lightning Web Components (LWC) stop working in that situation. It also covers the workarounds people reach for and what each costs. The rest of the tutorial builds the solution, Lightning Message Service (LMS).
Prerequisites
This chapter assumes you already know:
- Basic LWC: templates, JavaScript classes, and decorators such as
@apiand@wire. - Lifecycle hooks such as
connectedCallbackanddisconnectedCallback. - How a Salesforce DX project is laid out and how to deploy metadata.
- How to place components on a Lightning page with Lightning App Builder.
You don't need any Aura or Visualforce experience yet. Later chapters cover both.
How components normally communicate
LWC has two built-in ways for components to exchange data, and both depend on the component tree.
| Direction | Mechanism | Who initiates |
|---|---|---|
| Parent to child | Public property (`@api`) | Parent sets a value in its template |
| Parent to child | Public method (`@api` method) | Parent calls the method on the child element |
| Child to parent | `CustomEvent` | Child dispatches, parent listens |
Here is a minimal working example. The child shows a button and tells its parent when it is clicked.
// recordItem.js
import { LightningElement, api } from 'lwc';
export default class RecordItem extends LightningElement {
@api recordId;
@api label;
handleClick() {
this.dispatchEvent(
new CustomEvent('select', {
detail: { recordId: this.recordId }
})
);
}
}<!-- recordItem.html -->
<template>
<button onclick={handleClick}>{label}</button>
</template>The parent places the child in its own template, passes values down through attributes, and listens for the event with an on prefix.
<!-- recordPicker.html -->
<template>
<c-record-item record-id="001000000000001" label="Acme" onselect={handleSelect}></c-record-item>
<c-record-item record-id="001000000000002" label="Globex" onselect={handleSelect}></c-record-item>
<p>Selected: {selectedId}</p>
</template>// recordPicker.js
import { LightningElement } from 'lwc';
export default class RecordPicker extends LightningElement {
selectedId;
handleSelect(event) {
this.selectedId = event.detail.recordId;
}
}This works because recordPicker owns the markup that contains c-record-item. It can set attributes on the child and attach a listener to it. The parent is the shared point where the two directions meet.
Where a Lightning page breaks the model
On a Lightning record page, an administrator drops components into regions with Lightning App Builder. Suppose a page has a list component in the left sidebar and a detail component in the main region.
The page and its regions belong to the platform. You can't edit their markup, so you can't add a listener or an attribute there. Each component you place becomes the root of its own tree.
This leaves three facts:
recordListandrecordDetailare siblings at best, and often further apart than that.- The only common ancestor is platform-owned and not something your code can write to.
- The components may not even be written in the same technology. One can be LWC, another Aura, and a third a Visualforce page embedded in the page.
The same problem appears outside record pages. It also shows up in utility bar items, console apps with several tabs, and any layout where an admin, not a developer, decides which components appear together.
Why the usual tools fail
Public properties and methods
An @api property is set by whatever component renders the element. recordDetail can only receive a value if its parent passes one. On the page, its parent is the platform, which knows nothing about your list's selection. Public methods fail for a related reason. A parent must hold a reference to the child element, for example through this.template.querySelector. Siblings can't query each other's elements. That would also break encapsulation, which the shadow DOM exists to enforce.
Custom events
A CustomEvent travels from the dispatching element upward through its ancestors. A listener must sit on the target or on one of its ancestors to hear it. recordDetail is not an ancestor of recordList, so it never sees the event, however you name it.
bubbles and composed do not rescue you
The bubbles and composed options control how far an event travels up the tree. Setting bubbles: true lets the event pass through ancestors. Adding composed: true lets it cross shadow DOM boundaries. Neither option sends the event sideways to a sibling.
An event with both flags set will pass up through the page's platform-owned elements. A listener attached to document could then catch it. That approach has serious problems:
- It depends on how the page is assembled, which Salesforce can change.
- Lightning's security layer (Lightning Locker or Lightning Web Security) can restrict what your code sees and attaches to outside its own namespace.
- Any component can listen to or spoof the event name, because the whole page is the audience.
- It does not reach Aura or Visualforce components in a reliable, supported way.
Treat document-level listeners as a pattern to avoid, not a technique to learn.
Workarounds and their costs
Developers have tried several approaches before LMS existed. Knowing why they fall short explains the design of LMS.
| Approach | How it works | Limitation |
|---|---|---|
| Wrapper parent component | A new component contains both children and passes data between them | You must own both children, and an admin can no longer place them independently. Only works inside LWC. |
| `pubsub` module | A shared JavaScript module keeps a list of callbacks keyed by event name | LWC only, no Aura or Visualforce, and you maintain the module. It also needs care on pages with several instances. |
| Aura application events | Aura components fire events that every Aura listener on the page receives | Aura only, and LWC can't join without an Aura wrapper. |
| Shared state in a JavaScript module | Both components import one module and read or write values | Nothing notifies the other component of a change. Modules may not be shared across namespaces. |
| Server round trip | One component saves to a record or custom setting, the other queries it | Slow, costs a request, and persists data that is only meant to be temporary. |
A wrapper component deserves a closer look because it is the first thing most developers try. It does work when both pieces are yours and a fixed layout is acceptable. Once the layout is configurable, or one component is a managed package component or a Visualforce page, it stops being possible.
What LMS changes
Lightning Message Service replaces the missing parent with a shared contract. Instead of components finding each other through the tree, each one connects to a named message channel. The channel is a piece of metadata that you deploy to the org. A component publishes a message to the channel, and any component that has subscribed to it receives the message. Neither side knows the other exists.
The next chapters cover each part:
- What LMS is and where it works.
- Defining and deploying the channel as metadata.
- Using
MessageContext,publish,subscribe, andunsubscribe. - Controlling who receives a message with scope.
- Connecting Aura and Visualforce to the same channel.
Because the channel is the only coupling point, components stay independent. You can add, remove, or replace either side without touching the other.
Common errors when facing this problem
- Raising a custom event from a sibling and expecting a response. The event goes up, not across. Check whether the target component is an ancestor of the dispatcher before relying on an event.
- Trying to call an
@apimethod on a component you cannot reach. Ifthis.template.querySelectorreturnsnull, the element is not in your template, and no other lookup will find it. - Adding
bubbles: true, composed: trueuntil something works. This widens the event's reach and hides the real design problem. It also exposes the event to every ancestor on the page. - Building a wrapper that hard-codes the layout. It solves today's page and breaks when an admin moves a component or a second team adds another one.
- Storing temporary UI state in a record. A selection that lasts a few seconds does not belong in the database.
Exercises
Exercise
A Lightning record page has a recordList component in the sidebar and a recordDetail component in the main region. The list dispatches new CustomEvent('selected', { detail: { id }, bubbles: true, composed: true }). Why can't recordDetail reliably receive this event with a normal listener, and what is the missing ingredient?
Show answer
Events travel up through the dispatcher's ancestors, and recordDetail is not one of them. It is a sibling in a different region, so no listener on recordDetail or its ancestors can see the event. bubbles and composed extend upward reach, not sideways reach. The missing ingredient is a shared parent that you own, or some other channel outside the component tree that both components can reach. LMS provides that channel.
Exercise
You are asked to let a Visualforce page, an Aura component, and an LWC on the same Lightning page share a selected account Id. Pick two workarounds from the table in this chapter, and explain why each fails for this requirement.
Show answer
Any two of these are correct. A wrapper parent component fails because the Visualforce page and the Aura component cannot be placed inside an LWC wrapper in a supported way, and admins lose the freedom to place them independently. The pubsub module fails because it is LWC only. Aura application events fail because only Aura components hear them. Shared JavaScript module state fails because it notifies nobody of changes and may not be shared across namespaces. A server round trip works technically but is slow and stores temporary state in the database.