The independent daily for Salesforce admins, developers and architects

Curated by Abhinav (opens in a new tab)

Five ways Lightning Web Components can share data between components (opens in a new tab)

You will see how a parent passes data to a child, how a child reports back, and when to use Lightning Message Service or Lightning Data Service instead.

Why read this

The piece also lists common mistakes to avoid.

Parent to child

  • @api public property
  • Parent sets HTML attribute
  • Child reads the value

Child to parent

  • Child dispatches CustomEvent
  • Detail carries the payload
  • Parent handles the event
Parent-to-child uses public properties; child-to-parent uses custom events

The article surveys five ways Lightning Web Components can communicate. The simplest is parent-to-child communication through a public property marked with the @api decorator, where the parent sets an HTML attribute and the child receives it. Code examples show a child component declaring a message property and a parent passing a welcome string into it.

When a child needs to notify its parent, it dispatches a custom event carrying a detail payload. The example has a child button fire a valuechange event, and the parent handles it and stores the selected value. The author notes that this lets the child report upward without reaching into the parent’s internal properties.

For components with no parent-child relationship, such as a customer information panel and a related sales panel, the article describes Lightning Message Service. The steps are to create a message channel, import it into a publisher, publish a message, subscribe in the receiving component and process the payload. Lightning Data Service is presented for cases where the data is a Salesforce record, using getRecord through a wire adapter, with the benefit of caching and record sharing across components. Shared JavaScript modules are mentioned for reusable logic.

The article closes with a table matching each method to its best use and a list of mistakes to avoid, such as using custom events where a public property is enough, creating unnecessary message channels, and calling Apex when Lightning Data Service already covers the need.

Read the original at dev.to (opens in a new tab)

Worth reading?