Mytutorialrack

In Lightning Web Components (LWC), lwc decorators plays a very important role in controlling the behavior of properties and methods in your components. They allow you to:  

1. Expose data or methods to other components.  

2. Track changes to properties for reactivity.  

3. Connect to Salesforce data sources.

In this blog, we will go into detail about the three main lwc decorators —@api, @track, and @wire—with examples, best practices, and some common use cases.

@api: Exposing Properties and Methods

The @api decorator is used to make a property or method public. Public properties can be accessed and modified by a parent component, while public methods can be called directly from the parent.

  • To expose a public property, decorate a field with @api. Public properties define the API for a component.
  • To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.

Let’s discuss with some examples: of lwc decorators

Example 1: Passing Data to a Child Component

Child Component :

childComponent.js

import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api message; 
} 

 childComponent.html 

<template>
    <p>Message from the parent: {message}</p>
</template>
 
Parent Component

parentComponent.html:

<template>
    <c-child-component message="Hello from Parent"></c-child-component>
</template>

  • The parent component passes the value “Hello from Parent” to the message property of the child component.
  • The child component displays this value in its template.

Example 2: Calling a Public Method in a Child Component

Child Component

childComponent.js

import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api handleClick() {
        alert('Method in the child component was called!');
    }
}
  
Parent Component

parentComponent.js 

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
    callChildMethod() {
        this.template.querySelector('c-child-component').handleClick();
    }
}
  

parentComponent.html 

<template>
    <c-child-component></c-child-component>
    <button onclick={callChildMethod}>Call Child Method</button>
</template>
 

By clicking the button in the parent component triggers the `handleClick` method in the child component.

@track: Tracking Changes in Properties

The @track decorator is used to make private properties reactive. If a property is decorated with @track, any change to its value automatically updates the DOM (Document Object Model).

Previously, you had to use the @track decorator to make a field reactive. Beginning in Spring ’20, all fields in a LWC class are reactive. If a field’s value changes, and the field is used in a template or in a getter of a property that’s used in a template, the component rerenders and displays the new value. If a field is assigned an object or an array, the framework observes some changes to the internals of the object or array, such as when you assign a new value.

You still need to decorate a field with @track in these use cases:

  • Observing changes to the properties of an object
  • Observing changes to the elements of an array

NOTE

  • Properties like String or Number in LWC are reactive by default and @track decorator is not needed.
  • Properties like arrays and objects need @track to detect changes and update the UI.

Let’s discuss with some examples of lwc decorators: Reactive Arrays

Imagine having a list of items that you want to update dynamically.

trackArr.js:

import { LightningElement, track } from 'lwc';

export default class TrackExample extends LightningElement {
    @track items = ['Apple', 'Banana', 'Cherry'];

    addItem() {
        this.items.push('Mango'); // Adding an item to the array
    }
}


trackArr.html:

<template>
    <ul>
        <template for:each={items} for:item="item">
            <li key={item}>{item}</li>
        </template>
    </ul>
    <button onclick={addItem}>Add Mango</button>
</template>

What Happens?

  • When the “Add Mango” button is clicked, the items array is got updated.
  • Since the array is marked with @track, the UI automatically updates to show the new item.

@wire: Fetching Salesforce Data

The @wire decorator connects your component to Salesforce data, such as records or Apex methods. It automatically fetches and binds data to your component, making it reactive.

To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adapter or an Apex method.

How @wire Works

  1. @wire can fetch Salesforce records using built-in APIs (like lightning/uiRecordApi).
  2. @wire can call custom Apex methods to fetch data or perform operations.

Let’s discuss with some examples of lwc decorators :

Example : Fetching Account Records

Let’s fetch a list of account records using the `getAccountList` Apex method.

Apex Controller (AccountController.apxc):

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name FROM Account LIMIT 10];
    }
}
 

 wireExample.js

import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';

export default class WireExample extends LightningElement {
    @wire(getAccountList) accounts; // Fetch account data
}
  

wireExample.html  

<template>
    <template if:true={accounts.data}>
        <ul>
            <template for:each={accounts.data} for:item="account">
                <li key={account.Id}>{account.Name}</li>
            </template>
        </ul>
    </template>
    <template if:true={accounts.error}>
        <p>Error: {accounts.error}</p>
    </template>
</template>

What Happens?

  • The @wire decorator fetches account data from the Apex method.
  • If the data is successfully fetched then it will be displayed in a list. If there’s an error, it will show the error to the user.

Best Practices for @wire:

  • Use @wire for reactive data fetching from salesforce.
  • Mark your Apex methods as @AuraEnabled annotation for better performance.

A Quick Comparison of LWC Decorators

DecoratorUse CaseExample
@apiParent-to-child communicationPassing or receiving data
@trackTracking changes in private propertiesUpdating a list or nested objects
@wireFetching Salesforce data (records or Apex)Displaying records like Accounts

Benefits of lwc decorators

Declarative SyntaxLwc decorators simplifies the code and makes the components easier to read and maintain.
ReusabilityLwc decorators promotes modular design by enabling clear communication and encapsulation.
ReactivityLwc decorators automatically updates the UI when data changes, reducing manual work.
IntegrationLwc decorators makes it easy to connect with Salesforce data and APIs.
PerformanceLwc decorators optimizes performance by reducing unnecessary computations and server calls.

Conclusion

Lwc decorators—@api, @track, and @wire : allows you to create flexible, reactive, and data-driven components. By understanding their use cases and limitations, you can build powerful Lightning Web Components with ease.

You can deepen your understanding of Lightning Web Components by exploring our comprehensive course on LWC.

You can explore more about Lightning Web Components through this video and check out our latest blogs on our websites for additional knowledge about salesforce.

Share:

Recent Posts