Sub topic 1
Fields in a Lightning web component
Prerequisites
This chapter assumes basic modern JavaScript, including classes, modules, and spread syntax. You should also know that a Lightning web component (LWC) has an HTML template and a JavaScript class.
Fields in a Lightning web component
A field is a value stored on the component class. The template can read a field through an expression such as {count}. The field belongs to the component instance, so methods access it with this.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
count = 0;
increment() {
this.count += 1;
}
}<template>
<lightning-button label="Add one" onclick={increment}></lightning-button>
<p>Count: {count}</p>
</template>Every field is reactive
A field is reactive when LWC watches its value and can update the template after that value changes. Plain fields are reactive by default. You do not need @track for a number, string, Boolean, or another value that you replace.
The important condition is that the template must read the field. LWC tracks values used during rendering. If a field is never used by the template, changing it does not create a visible update.
What actually triggers a rerender
A rerender is a new evaluation of the template. Assigning a new value to a field triggers it when the field is a template dependency.
this.count = this.count + 1;The assignment changes the field's value. LWC then schedules the component for rendering. Rendering is normally asynchronous, so several changes may be combined before the browser updates the page.
Reassigning versus mutating objects and arrays
Objects and arrays are reference values. Changing a property or item keeps the same reference:
this.profile.name = 'Grace';
this.items.push('New item');Without @track, these mutations do not reliably trigger a rerender. Reassign a new object or array instead:
this.profile = { ...this.profile, name: 'Grace' };
this.items = [...this.items, 'New item'];The spread syntax creates a new reference, so LWC detects the field assignment. This approach also makes updates easier to reason about. Later chapters explain when @track can observe nested mutations.
Exercise
How should you add "Paris" to a reactive array named cities?
Show answer
Use this.cities = [...this.cities, 'Paris']; so the field receives a new array reference.