Exploring the @track Decorator in Salesforce LWC: A Detailed Guide with Examples

@track decorator in LWC
Chinmaya By Chinmaya
5 Min Read

Introduction

In Salesforce Lightning Web Components (LWC), decorators play a pivotal role in controlling the behaviour of properties within components.

Among these, the @track decorator is used to make properties reactive, allowing the LWC component to update the UI dynamically when the property’s value changes.

This blog post explores the @track decorator, its current relevance, and practical use cases with examples.

If you’re unfamiliar with Decorators, I recommend checking out the posts below to learn about the different types of LWC decorators in Salesforce.

What is the @track decorator?

The @track decorator in Salesforce Lightning Web Components (LWC) is used to make a JavaScript property reactive.

When you add @track to a property, any changes to that property automatically update the component’s UI.
This means the component will re-render whenever the tracked property’s value changes.

Note: we can’t access @track properties from outside as they are private and only accessible within its component only.

When to use @track Decorator?

    1. Monitor changes to the properties of objects and arrays within a component
    2. Ensure that the component re-renders when the content of these data types changes
    3. Enhance the reactivity of private properties
    4. Track a private property and re-render the component when that property changes

Since Salesforce Spring ’20, all fields in a Lightning Web Component are reactive by default. If a field is used in a template and its value changes, the component automatically re-renders to display the updated value.

However, you still need to use the @track decorator in the following scenarios:

    1. Tracking changes to the properties of an object.
    2. Tracking changes to the elements of an array.

Syntax and Usage

To declare a reactive property using @track

Javascript:

				
					import { LightningElement, track } from 'lwc';

export default class ExampleComponent extends LightningElement {
    @track trackedObject = { key: 'value' };
    @track trackedArray = [];
}
				
			

Example 1 : Reactive Objects with @track

This example demonstrates how changes to an object’s property update the UI dynamically when using @track.

JavaScript: exampleComponent.js

				
					import { LightningElement, track } from 'lwc';

export default class ExampleComponent extends LightningElement {
    @track user = {
        firstName: 'John',
        lastName: 'Doe'
    };

    handleChange() {
        this.user.firstName = 'Nick'; // Updates UI immediately
    }
}
				
			

HTML: exampleComponent.html

				
					<div>
    <p>First Name: {user.firstName}</p>
    <p>Last Name: {user.lastName}</p>
    <button onclick={handleChange}>Change First Name</button>
</div>
				
			

Output

Initially

				
					First Name: John
Last Name: Doe
				
			

After clicking the button:

				
					First Name: Jane
Last Name: Doe
				
			

Example 2 : Reactive Arrays with @track

Here, we update an array and reflect the changes in the UI.

JavaScript: exampleComponent.js

				
					import { LightningElement, track } from 'lwc';

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

    addItem() {
        this.items.push('Grapes');
    }
}
				
			

HTML: exampleComponent.html

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

Output

Initially

				
					Apple
Banana
Orange
				
			

After clicking the button:

				
					Apple
Banana
Orange
Grapes
				
			

Key Points to Remember

  1. Default Reactivity in LWC:
      • •Primitive properties (e.g., string, number, boolean) are reactive by default.
      • •Properties in simple objects are also reactive unless nested.
  2. When to Use @track:
      • •Use @track for nested object properties or arrays where reactivity is required.
      • •For deeply nested objects, consider replacing the entire object instead of updating specific properties for better performance.
  3. Deprecation Rumors:
      • •While @track is still supported, its usage has diminished with the enhanced default reactivity of LWC.

Checkout below posts to explore other 2 LWC Decorators in Salesforce

Conclusion

In simple words, the @track decorator tells the LWC to watch the property for any changes. If there are any changes to the property, then update the UI automatically.

The @track decorator is a valuable tool for handling reactivity in Salesforce LWC, particularly for nested data structures.

While it has become less essential due to the framework’s improved default reactivity, it remains an important part of an LWC developer’s toolkit.

For more in-depth guides and examples on LWC and Salesforce development, visit Writtee.com. If you have questions or experiences with @track, feel free to share them in the comments below!

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
3 Comments