Sub topic 12
When events are not the right tool
This chapter assumes you can create and dispatch a CustomEvent, handle it in a parent template, and read event.detail. It also assumes you know how bubbles and composed affect propagation. Events cover one direction well: a child tells its parent that something happened. Other communication needs call for other tools.
Match the pattern to the direction
Choose by asking who needs to talk to whom.
| Need | Pattern | Reason |
|---|---|---|
| Send data to a child | `@api` property | Data flows down. No event is involved. |
| Ask a child to do something | `@api` method | The parent calls the child directly. |
| Signal that something happened to a parent | `CustomEvent` | The child stays unaware of who listens. |
| Talk across unrelated parts of a page | Lightning Message Service (LMS) | Events only travel up the DOM tree. |
| Share state between components in one app | Shared JavaScript module | Every importer sees the same module instance. |
Parent to child: properties and methods
A parent should never use an event to send data down. Set a public property instead. When the parent must trigger an action, such as clearing a form, expose an @api method on the child and call it.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
highlighted = false;
@api
reset() {
this.highlighted = false;
}
}// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
handleClear() {
const tile = this.template.querySelector('c-product-tile');
if (tile) {
tile.reset();
}
}
}Keep these methods few. A child with many imperative methods is hard to reuse, because every parent must know the order in which to call them. Prefer a property when the value is state, and a method only when the request is a one-time command.
Unrelated components: Lightning Message Service
Events travel up the DOM tree from the dispatching element. Two sibling components in different regions of a page have no shared path. Relaying an event through every ancestor makes each intermediate component carry code that is not its concern.
Lightning Message Service lets components publish and subscribe on a named channel, with no DOM relationship. You first define a message channel in your project as metadata. You then import it and publish to it.
// filterPublisher.js
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import PRODUCT_SELECTED from '@salesforce/messageChannel/ProductSelected__c';
export default class FilterPublisher extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect() {
publish(this.messageContext, PRODUCT_SELECTED, { productId: 'p1' });
}
}Subscribers use subscribe with the same channel and unsubscribe when they are removed from the page. A subscriber that never unsubscribes keeps receiving messages and leaks memory.
Shared state: a plain JavaScript module
If several components in the same application read and write the same data, you can put it in an ordinary ES module. All components that import the module share one instance.
// cartStore.js
const items = [];
const listeners = new Set();
export function addItem(item) {
items.push(item);
listeners.forEach((fn) => fn([...items]));
}
export function subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}This is lighter than LMS when everything is in your own bundle. It does not cross Aura or Visualforce boundaries, so use LMS when the page mixes frameworks.
Common mistakes
- Using an event to pass data down. The parent already owns the child's element, so set a property.
- Dispatching with
bubbles: true, composed: trueto reach a distant component. Every ancestor and listener in the path sees the event, which couples components that should be independent. Reach for LMS instead. - Reaching into a child's DOM. Querying
childElement.shadowRootis not supported. Use@apimembers. - Forgetting to unsubscribe from LMS or a shared store in
disconnectedCallback.
Exercise
Two components, a filter panel and a results table, sit in different regions of a Lightning page and share no common parent component you control. The filter panel must tell the results table which category the user chose. Which pattern fits, and why is a bubbling, composed CustomEvent a poor choice?
Show answer
Use Lightning Message Service, or a shared module if both components are in your own bundle and framework. A CustomEvent only travels up from the element that dispatches it, so it cannot reach a component that is not an ancestor. Making it bubble and compose would still not reach the results table, and it would expose the event to every ancestor along the way.
Exercise
A parent wants to clear a child's selected state when the user presses a "Reset" button in the parent. Should the child expose an event, a property, or a method?
Show answer
An @api method such as reset() fits, because the parent is issuing a one-time command to the child. A property also works if the child's state is fully driven by a value the parent sets. An event is wrong, because events carry information from child to parent.