Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Lightning Web Components

LWC Reactivity, Events and Component Communication

Understand LWC reactive properties, event handlers, CustomEvent from child to parent, @api methods and the Lightning Message Service, with runnable JavaScript stand-ins.

A web page is only useful if it responds. In Lightning Web Components, reactivity means the template updates when data changes, and events let components talk to each other. Data flows down from parent to child through @api properties; messages flow up through events. For unrelated components on the same page, the Lightning Message Service provides a channel. This lesson covers all three, building on your first component.

LWC cannot run here. The LWC listings are read-only; the runnable examples are plain JavaScript stand-ins for the mechanisms, labelled as such.

Reactive properties

Since Spring '20, every class field is reactive: when you reassign it, the component re-renders. You do not need @track for primitives or for replacing a whole object or array.

JavaScript
import { LightningElement } from 'lwc';

export default class Counter extends LightningElement {
    count = 0;

    handleClick() {
        this.count = this.count + 1;   // re-renders
    }
}
HTML
<template>
  <lightning-button label="Add one" onclick={handleClick}></lightning-button>
  <p>Count: {count}</p>
</template>

Reactivity detects reassignment. Changing something deep inside an object or array (this.items.push(x), this.user.name = 'Ana') is not noticed unless the field is decorated with @track, or you replace the value with a new one:

JavaScript
this.items = [...this.items, newItem];       // reactive, preferred
this.user = { ...this.user, name: 'Ana' };   // reactive

Prefer immutable updates; they are easier to reason about than @track.

Handling events

Standard DOM events use on plus the event name in the template, with the handler a method on the class:

HTML
<lightning-input label="Name" onchange={handleChange}></lightning-input>
JavaScript
handleChange(event) {
    this.name = event.target.value;
}

Handlers must be bare method names (onclick={handleClick}); you cannot pass arguments in the template. Use data- attributes and read event.target.dataset:

HTML
<button data-id={row.Id} onclick={handleSelect}>Select</button>
JavaScript
handleSelect(event) {
    const id = event.target.dataset.id;
}

Child to parent: CustomEvent

A child announces that something happened by dispatching a CustomEvent. Event names should be lowercase with no spaces or hyphens.

JavaScript
// child: contactRow.js
import { LightningElement, api } from 'lwc';

export default class ContactRow extends LightningElement {
    @api contact;

    handleSelect() {
        this.dispatchEvent(new CustomEvent('select', {
            detail: { contactId: this.contact.Id }
        }));
    }
}
HTML
<!-- parent template -->
<c-contact-row contact={c} onselect={handleContactSelect}></c-contact-row>
JavaScript
// parent
handleContactSelect(event) {
    this.selectedId = event.detail.contactId;
}

The detail should be plain data (not objects the child may mutate). By default the event does not bubble past the parent; options bubbles and composed change that, but use them sparingly because they tie components together.

Parent to child: @api methods

A parent can call a public method of a child through this.template.querySelector:

JavaScript
// child
@api reset() { this.value = ''; }

// parent
handleClear() {
    this.template.querySelector('c-search-box').reset();
}

Property updates are the better default; reserve @api methods for imperative actions such as focus() or reset().

Unrelated components: Lightning Message Service

Two components that are not parent and child (a list and a detail panel placed separately on a page) communicate through a message channel, defined in an XML file Selected.messageChannel-meta.xml, then:

JavaScript
import { LightningElement, wire } from 'lwc';
import { publish, subscribe, MessageContext } from 'lightning/messageService';
import SELECTED from '@salesforce/messageChannel/Selected__c';

export default class Publisher extends LightningElement {
    @wire(MessageContext) messageContext;

    announce(id) {
        publish(this.messageContext, SELECTED, { recordId: id });
    }
}

A subscriber calls subscribe(this.messageContext, SELECTED, handler) in connectedCallback and unsubscribes in disconnectedCallback (see lifecycle hooks).

Try the idea: reactivity by reassignment (JavaScript stand-in)

JS Stand-in: re-render when a field is reassigned (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This stand-in watches only top-level assignments, which is exactly why push goes unnoticed in LWC without @track. (Real LWC uses its own tracking, not a Proxy, but the visible rule is the same.)

Try the idea: child event up, property down (JavaScript stand-in)

JS Stand-in: a child dispatches an event, the parent updates (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rules of thumb

  • Data down (@api), events up (CustomEvent).
  • Replace objects and arrays instead of mutating them.
  • Keep event names lowercase; put data in detail.
  • Use the message service or a state module for distant components, not bubbles: true, composed: true everywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement triggers a re-render in LWC without any decorator?

    Reassigning a field is detected. Mutating inside an object or array is not, unless the field is @track.
  2. 2. How does a child component tell its parent that something happened?

    Events flow up from child to parent.
  3. 3. How do you read which row's button was clicked when the handler cannot take arguments?

    A data-id attribute on the element is available as event.target.dataset.id inside the handler.
  4. 4. Which tool lets two unrelated components on a page exchange messages?

    Message channels with publish and subscribe connect components that are not in the same hierarchy.

Summary

  • Fields are reactive on reassignment; use immutable updates for objects and arrays.
  • Handlers are method names; read extra data from dataset.
  • Child to parent: CustomEvent with data in detail; parent to child: @api properties and methods.
  • Unrelated components: Lightning Message Service.

Next: Calling Apex from LWC with @wire and Imperative Calls