Sub topic 11
Designing Events Well
This chapter assumes you can already create and dispatch a CustomEvent, listen for it in a parent template, and read event.detail. It also assumes you know what bubbles and composed do. Here we collect the design decisions that keep events easy to understand, easy to test, and hard to misuse.
Why design matters for events
A public event is part of a component's API, just like an @api property. Once other components listen for productselected, you can't rename it or change its payload without breaking them. Most event problems come from decisions made quickly at the start:
- A vague name that later means two different things.
- A payload shaped around the sender's internals.
- Propagation settings widened until the bug went away.
The guidelines below address each of these.
Name events for what happened
An event announces a fact that already occurred. It doesn't command the parent to do something. The child doesn't know what the parent will do with the signal, and it shouldn't.
| Weak name | Why it is weak | Better name |
|---|---|---|
| `updateparent` | Describes the child's wish, not the fact | `productselected` |
| `click2` | Says nothing about meaning | `quantitychange` |
| `onselect` | The `on` prefix collides with the handler attribute | `select` or `productselected` |
| `ProductSelected` | Uppercase letters are not allowed | `productselected` |
| `product-selected` | Hyphens are discouraged and break convention | `productselected` or `product_selected` |
The naming rules to follow:
- Use lowercase letters, numbers, and underscores only, and start with a letter.
- Don't start the name with
on. The parent adds that prefix in the template, soonproductselectedis the attribute forproductselected. - Prefer a past-tense or state-change name (
productselected,filterchange) over an imperative one (selectproduct). - Keep names specific to the component's job. Generic names like
changeandselectalready exist for standard HTML elements and are easy to confuse with them.
If you name an event select, remember that the browser also has events with that name. A parent listening with onselect on your component may receive a native event instead, or as well.
Keep the payload small and safe
The detail object is the contract between sender and receiver. Treat it as data, not as a handle on the child.
Send the minimum the parent needs
Send identifiers and the changed values, not the child's whole state. A parent that needs more can look it up by id. A small payload is also easier to keep stable across versions.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
@api record;
handleSelect() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: {
productId: this.productId,
name: this.name
}
})
);
}
handleSelectCopy() {
// If you must send an object, send a copy, never the original.
this.dispatchEvent(
new CustomEvent('productselectedwithrecord', {
detail: { record: { ...this.record } }
})
);
}
}Never send `this`, DOM nodes, or shared objects
Don't put these in detail:
- The component instance (
this). - Elements from
this.template. - Functions that reach into the child's private state.
- Objects the child keeps using.
Listeners can mutate whatever they receive. If the child sends a reference to its own array and the parent calls push on it, the child's state changes silently. Data passed down through @api is also wrapped in a read-only proxy. Reusing such an object in a payload gives the parent something it can't modify and may not expect. Copy first, as handleSelectCopy does above. The spread operator makes a shallow copy. Nested objects still share references, so copy deeper levels too when the parent might change them.
Make the payload serializable in spirit
Stick to strings, numbers, booleans, arrays, and plain objects. You don't have to call JSON.stringify, but data you could stringify is data that behaves the same under any parent, test, or future refactor.
Keep the shape stable
Adding a new key to detail is safe for existing listeners. Renaming or removing a key breaks them. If you expect to add fields over time, always send an object, even for a single value. detail: { productId } can grow. detail: 'p1' can't.
Dispatch at the right moments
Dispatch in response to something real: a user action, a completed operation, or a meaningful state change. Be careful with these cases:
renderedCallback: It runs after every render. If the parent's handler changes state that causes a re-render, you can create an infinite loop. Guard any dispatch from this hook with a flag, or move it to the code path that actually caused the change.constructor: The component has no host element attributes yet, and you can't dispatch from it in a useful way.connectedCallback: Template listeners attached by the parent are normally in place, so dispatching works. Even so, an event announcing "I am ready" is often a sign the parent should read state some other way.- Bursts of events: For rapid input such as typing, dispatch on a completed change, or debounce the dispatch. Don't send one event per keystroke unless the parent really needs it.
Choose the narrowest propagation
By default a CustomEvent has bubbles: false and composed: false. It fires on the child's host element and goes no further, so only the direct parent's listener on that element sees it. This is the safest setting. Widen it only with a reason.
| Setting | Who can receive it | Use it when |
|---|---|---|
| Neither (default) | Listeners on the child element itself | Parent and child talk directly. This covers most cases. |
| `bubbles: true` | Ancestors inside the same shadow tree, up to the parent template's root | A wrapper element in the parent's template should catch events from several children. |
| `bubbles: true, composed: true` | Ancestors across every shadow boundary, up to the document | Almost never. Reserve it for events meant to be public across the whole page. |
A composed event leaks the child's internals to every ancestor and can be received by components that were never meant to depend on it. It also makes your event name effectively global. Two unrelated components that both use change with composed: true can interfere with each other. If you need to reach a component several levels up, consider the alternatives below before reaching for composed.
If an intermediate parent needs to pass the signal upward, relay it. The middle component listens, then dispatches its own event with a name that makes sense at its level. Each level then has a small, documented contract instead of one event that tunnels through everything.
Keep handlers on the parent side simple
The parent's job in a handler is to read event.detail and update its own state. A few habits keep this reliable:
- Read from
event.detail, not from the child element. Calling methods or reading properties onevent.targetties the parent to the child's internals. - Don't mutate
event.detail. Treat it as read-only, even though it isn't enforced. - Call
event.stopPropagation()only when you have a reason, such as an event that bubbles and shouldn't reach higher ancestors. Stopping propagation by habit hides events from components that legitimately need them. - Remove listeners you add in JavaScript if the component can be disconnected and reconnected. For a handler attached in
connectedCallback, remove it indisconnectedCallback.
Document the contract
LWC has no schema for events, so write the contract down. A short comment above the dispatch is enough. State the event name, when it fires, and the shape of detail.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
/**
* Fired when the user clicks the tile.
* Event: productselected
* detail: { productId: string, name: string }
* bubbles: false, composed: false
*/
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId, name: this.name }
})
);
}
}A test is the other half of the contract, because it fails when someone changes the name or payload by accident.
Test the design decisions
You can test more than "the event fires". You can check that the payload is exactly what you documented and that the event does not escape by default.
// productTile.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('c-product-tile event contract', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('sends only productId and name in detail', () => {
const element = createElement('c-product-tile', { is: ProductTile });
element.productId = 'p1';
element.name = 'Desk';
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail).toEqual({
productId: 'p1',
name: 'Desk'
});
});
it('does not bubble beyond the host element', () => {
const element = createElement('c-product-tile', { is: ProductTile });
document.body.appendChild(element);
const bodyHandler = jest.fn();
document.body.addEventListener('productselected', bodyHandler);
element.shadowRoot.querySelector('button').click();
expect(bodyHandler).not.toHaveBeenCalled();
document.body.removeEventListener('productselected', bodyHandler);
});
});The second test locks in the default propagation. If someone later adds composed: true to fix a problem elsewhere, the test fails and prompts a conversation.
Know when an event is the wrong tool
Events carry a signal upward along the component tree. They are a poor fit when:
- The receiver is not an ancestor. Two sibling components, or components in different regions of a page, can't hear each other's events. Use a shared service module, or Lightning Message Service when the components live on a Lightning page.
- The parent needs to tell the child something. That direction uses
@apiproperties or@apimethods, not events. - The data is shared and long-lived. If many components read and write the same state, put it in a shared JavaScript module instead of passing it through events at every level.
- The signal must pass through many layers. Relaying through five components is a sign of a structure problem. A shared module or message channel may be simpler.
Common mistakes
- Naming the event with uppercase letters or an
onprefix, so the parent's handler never attaches. - Using
composed: trueto "make it work" when the real problem is an attribute typo in the parent template. - Sending
thisor an internal array indetail. - Dispatching from
renderedCallbackwithout a guard. - Reading
event.targetin the parent to get data that belongs indetail. - Adding a listener in
renderedCallbackon every render without a guard flag.
Exercise
A child component dispatches new CustomEvent('ItemSaved', { detail: this.items, bubbles: true, composed: true }). List the problems and give a corrected version.
Show answer
Problems: (1) The name has uppercase letters, which is not allowed, so use itemsaved. (2) detail is the child's own this.items array, so a listener can mutate the child's state; send a copy or only the needed fields. (3) composed: true lets every ancestor across shadow boundaries receive it, and bubbles: true is probably unnecessary for a direct parent. Corrected: new CustomEvent('itemsaved', { detail: { items: [...this.items] } }), which uses the default propagation.
Exercise
Two sibling components on a page need to react when the other changes a filter. Why are custom events from one to the other a poor fit, and what should you use?
Show answer
A custom event travels up from the dispatching element to its ancestors, so a sibling never receives it. Use a pattern that doesn't depend on the component tree, such as a shared JavaScript module holding the state or Lightning Message Service. Alternatively, have the common parent listen to one sibling's event and pass the result to the other through an @api property.