Sub topic 12
When events are not the right tool
This chapter assumes you can already dispatch a CustomEvent from a child and handle it in a parent template. It also assumes you know how bubbles and composed work and are comfortable with @api properties. The chapter covers the cases where a custom event is the wrong choice and names what to use in its place.
What events are good at
A custom event is a signal that travels up the component tree. It fits best when a child reports something to the component that contains it: "the user picked a product", "the form was saved", "the dialog was closed". The child doesn't know who listens, and the parent decides what to do.
That fit is narrow. Events follow the DOM tree, so they work only along the path from a component up through its ancestors. Many communication problems don't follow that path. Some run downward, some run sideways between unrelated components, and some aren't about components at all.
Going down: properties and methods
Data that flows from parent to child should not use events. Use one of these two mechanisms.
- Public properties. The child exposes a field with
@api, and the parent sets it in the template. This is the default for passing state down. - Public methods. The child exposes a function with
@api, and the parent calls it. This suits commands such as "reset", "focus", or "validate", which are actions and not state.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
isHighlighted = false;
@api
highlight() {
this.isHighlighted = true;
}
@api
reset() {
this.isHighlighted = false;
}
}// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
handleClearClick() {
const tile = this.template.querySelector('c-product-tile');
if (tile) {
tile.reset();
}
}
}The if (tile) guard matters. querySelector returns null when the child isn't rendered, for example behind an if:true block.
Prefer a property when the child can derive its behavior from state. Reach for a method only when the parent needs to trigger an imperative action. A parent that calls many child methods in a fixed order is usually a sign that the state should live in a property instead.
A child must not modify an @api property it received. LWC treats those values as read-only from the child's side. If the child needs to change the value, it should dispatch an event and let the owner update the property. That pairing is the "properties down, events up" rule from the first chapter.
Going sideways: siblings
Two components that share a parent can't send events to each other directly. An event from one child goes up to the parent, not across to its sibling.
The standard solution is to let the parent act as a mediator. Child A dispatches an event. The parent handles it, stores the value in a field, and passes the value to child B through a property.
<!-- productPage.html -->
<template>
<c-product-list onproductselected={handleProductSelected}></c-product-list>
<c-product-detail product-id={selectedId}></c-product-detail>
</template>// productPage.js
import { LightningElement } from 'lwc';
export default class ProductPage extends LightningElement {
selectedId;
handleProductSelected(event) {
this.selectedId = event.detail.productId;
}
}This costs one handler and one field in the parent, and it keeps the data flow easy to trace. Use it whenever the siblings have a common parent that is a reasonable owner of the shared state. It stops working well when the components are far apart in the tree, because every intermediate component has to forward the data.
Going anywhere: Lightning Message Service
When two components have no useful common ancestor, a parent can't mediate. Examples are a component in a utility bar and one on a record page, or components in separate regions of a Lightning page. For these cases, Salesforce provides Lightning Message Service (LMS). It is a publish and subscribe mechanism that works across the Lightning page, including between LWC, Aura, and Visualforce.
LMS is specific to the Salesforce platform. It isn't part of open-source LWC, so it is unavailable if you build components outside Salesforce.
You define a message channel as metadata. The channel lists the fields a message may carry.
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>ProductSelected</masterLabel>
<isExposed>true</isExposed>
<description>Published when a user selects a product.</description>
<lightningMessageFields>
<fieldName>productId</fieldName>
<description>Id of the selected product.</description>
</lightningMessageFields>
</LightningMessageChannel>Save it as messageChannels/ProductSelected.messageChannel-meta.xml. The publisher imports the channel and calls publish.
// productPublisher.js
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import PRODUCT_SELECTED from '@salesforce/messageChannel/ProductSelected__c';
export default class ProductPublisher extends LightningElement {
@wire(MessageContext)
messageContext;
handleClick() {
publish(this.messageContext, PRODUCT_SELECTED, { productId: 'p1' });
}
}The subscriber subscribes when it connects and unsubscribes when it disconnects.
// productSubscriber.js
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import PRODUCT_SELECTED from '@salesforce/messageChannel/ProductSelected__c';
export default class ProductSubscriber extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
PRODUCT_SELECTED,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
this.selectedId = message.productId;
}
}Two details cause most LMS problems:
- Without
{ scope: APPLICATION_SCOPE }, a component receives messages only while it is the active one in its own context, such as the visible tab. For a component that should always listen, pass the scope option. - A subscription that is never removed keeps the component alive and keeps calling its handler. Always unsubscribe in
disconnectedCallback.
Shared state in a JavaScript module
Sometimes components inside one bundle of related components need the same state, and neither a parent nor a message channel is a good fit. A plain ES module can hold that state. Every component that imports the module gets the same instance, because modules are evaluated once.
// cartStore.js
const listeners = new Set();
let items = [];
export function getItems() {
return items;
}
export function addItem(item) {
items = [...items, item];
listeners.forEach((listener) => listener(items));
}
export function subscribeToCart(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}This is more code to maintain than an event, and it moves the state outside the component tree. Reactivity then depends on you: a component must subscribe, copy the data into one of its own fields, and unsubscribe when it disconnects. Choose it when many components read the same state and the tree gives no natural owner. Don't use it merely to avoid writing one event handler.
Not component communication at all
Many cases where developers reach for events are really about data, and the platform has tools for that.
- Record data. If two components show the same record, load it with Lightning Data Service, for example
getRecordthrough@wire. After one component saves, the other receives the updated record without any event.notifyRecordUpdateAvailabletells the cache that a record changed through some other route, such as Apex. - Apex-backed lists. When a child changes server data that a parent displays, the parent can refresh its own wire with
refreshApex. The child still needs to tell the parent that the change happened, so an event often remains the right signal. The refresh happens in the parent's handler. - Reusable markup with different content. If a parent only wants to put its own content inside a child, use a slot. Slotted content stays owned by the parent, so you don't need events to pass it.
Choosing between them
The same decision as a table:
| Situation | Pattern | Main cost |
|---|---|---|
| Parent passes state to a child | `@api` property | Child can't change it |
| Parent triggers an action in a child | `@api` method | Tighter coupling to the child |
| Child reports to its parent | `CustomEvent` | Only works up the tree |
| Siblings with a shared parent | Event, then property | Parent holds the state |
| Unrelated components on a page | Lightning Message Service | Metadata, subscription cleanup |
| Many components share local state | Shared JavaScript module | You manage reactivity yourself |
| Components show the same record | Lightning Data Service | Applies to records only |
Common mistakes
- Using a composed, bubbling event as a global broadcast. Setting
bubbles: trueandcomposed: truemakes the event travel through every ancestor. Any ancestor can intercept it, and the event name becomes a hidden contract across the whole page. If you need a broadcast, use LMS, where the channel is an explicit contract. - Calling
querySelectorto reach deep into another component. A parent can only query elements in its own template. It can't reach into the shadow tree of a child, and relying onlwc:dom="manual"or synthetic shadow tricks breaks when the platform changes. Pass data through@apiinstead. - Using an event where a property would do. If the parent already knows the value, don't have the child ask for it through an event. Pass it down.
- Using a method where a property would do. If the parent calls
child.setTitle('x')on every render, maketitlea property. - Forgetting the order of events and rendering. A parent handler that sets a field causes a re-render on the next microtask, not immediately. Code that reads the child's updated state right after dispatching may see the old state. Read the state in
renderedCallbackor after an awaited promise.
Exercise
A utility bar component and a record page component are unrelated in the DOM tree. The record page component must update when the utility bar component publishes a selected product. Which pattern fits, and what must the subscriber do to avoid leaking subscriptions?
Show answer
Use Lightning Message Service, since neither component can reach the other through the tree and a custom event can't travel between them. The subscriber should call subscribe in connectedCallback with APPLICATION_SCOPE so it receives messages when it isn't the active component, and call unsubscribe in disconnectedCallback so the handler stops running after the component is removed.
Exercise
A page has c-filter-panel and c-result-table as siblings inside c-search-page. When the user changes a filter, the table must reload. Describe the data flow without Lightning Message Service, and name the field that holds the shared state.
Show answer
c-filter-panel dispatches a custom event, for example filterchange, with the new filter in detail. c-search-page handles the event and stores the filter in a field such as currentFilter. The parent template passes that field to the table through a public property, for example filter={currentFilter}, and the table reloads when the property changes. The event travels up and the property travels down, so the siblings never reference each other.
Exercise
A parent calls this.template.querySelector('c-product-tile').reset() and sometimes throws "Cannot read properties of null". What is the cause and the fix?
Show answer
querySelector returns null when the child is not rendered, for example because it is inside a conditional block or the parent has not rendered yet. Guard the call with a null check, as in const tile = ...; if (tile) { tile.reset(); }, and make sure the code runs after the child has rendered, such as in an event handler or renderedCallback.