0

In the below code the greeting value is displayed in the component either 1 or 2 statement is used. then why we are using track decorator?

export default class HelloWorld extends LightningElement {
@track greeting = 'lwc World'; ---- 1
greeting = 'lwc World';        -----2
changeHandler(event)
{
    this.greeting = event.target.value;
}
}

2 Answers 2

1

From the documentation, the second paragraph explains when @track is needed. So it is not needed for your example. You may find it used unnecessarily in older code, as AFAIK in early versions of LWC it was required for simple properties too.

@track

Fields 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.

There is one use case for @track. When a field contains an object or an array, there’s a limit to the depth of changes that are tracked. To tell the framework to observe changes to the properties of an object or to the elements of an array, decorate the field with @track.

2
  • Thanks a lot Keith... Jan 23, 2021 at 15:48
  • 1
    I can confirm that @track was required before Spring '20 and getting used to not needing it any more is quite hard!
    – Phil W
    Jan 23, 2021 at 16:06
1

This community won't know your original intentions with the @track decorator it's no longer required so you can remove the annotation altogether at statement 1. You can also remove the line below it (statement 2) as it's redundant to statement 1.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .