Lightning Web Components: Are you still using @track?

Lightning Web Components: Are you still using @track?

There's no need for guesswork when it comes to making fields reactive in a Lightning web component class. Now, all fields are inherently reactive. Whenever a field's value undergoes a change, and that field is utilized within a template or in a getter of a property used within a template, the component will automatically trigger a rerender, displaying the updated value.

Why is my Lightning Web Component (LWC) still failing to render when a value is modified, even after the Spring '20 release - No need to use @track.

There is still a specific scenario where using @track remains relevant. When a field contains an object or an array, there exists a restriction on the depth of changes that are automatically tracked.

To instruct the framework to monitor changes within the properties of an object or elements of an array, you can annotate the field with @track.

In the absence of @track, the framework solely observes changes that involve assigning an entirely new value to a field. If the new value is not strictly equal (===) to the previous value, the component will initiate a rerender.

Example without using @t

basket = { fruit : '', Vegetable : '' };        
// Component rerenders.
this.basket = { fruit : 'Apple', Vegetable : 'Cabbage' };        
// Component doesn't rerender.
this.basket.fruit = 'Pineapple';        

To tell the framework to observe changes to the object's properties, decorate the basket field with @track. Now if we change either property, the component re-renders.

// Component rerenders.
@track basket = { fruit : '', Vegetable : '' };
this.basket.fruit = 'Pineapple';        
Shailendra Singh Parmar

Helping businesses to Maximize their Salesforce Investment | Salesforce AppExchange | Salesforce Partner | Salesforce Solution Architect | Founder at Astonous | Trailblazer

1 年

You are producing great content Gaurav Gupta. Keep going!

要查看或添加评论,请登录

Gaurav Gupta的更多文章

社区洞察

其他会员也浏览了