When Salesforce introduced Lightning Web Components (LWC), developers quickly learned that reactivity was tied to the @track decorator. Before Spring ’20, if you wanted your component to rerender when a property changed, you had to explicitly mark it with @track.
But after the Spring ’20 release, Salesforce simplified the reactivity model. Primitive properties (like strings, numbers, and booleans) and even top-level objects/arrays became reactive by default. This left many developers wondering: Is @track obsolete?
The short answer: not entirely.
When You Still Need @track
The catch lies in nested mutations inside objects or arrays. LWC does not automatically detect changes deep inside unless the property is decorated with @track.
Example:
import { LightningElement, track } from 'lwc';
export default class TrackExample extends LightningElement {
@track address = {
city: 'Nagpur',
country: 'India'
};
handleCityChange(event) {
this.address.city = event.target.value; // Nested mutation
}
}
Template:
<template>
<lightning-input label="City" value={address.city} onchange={handleCityChange}></lightning-input>
<p>City: {address.city}</p>
</template>
With @track: the <p> updates immediately when you type.
Without @track: the <p> won’t update unless you reassign the entire object:
this.address = { ...this.address, city: event.target.value };
Final Thoughts
@track isn’t gone — it’s just less common. Think of it as a tool for special cases rather than a default habit.
No comments:
Post a Comment