What is the role of the @track decorator, and when is it required in modern LWC development?
Answer
Basics: Reactive means "when this value changes, the template re-renders". Originally all reactive properties needed @track. Now a field like count = 0 is reactive on its own: this.count++ re-renders. The subtlety is objects and arrays: reassigning this.obj = {...} is detected, but this.obj.name = 'x' is not unless the field is tracked.
How it works:
- The engine observes only the reference held by a field by default (shallow).
- With
@track, the engine wraps the value in a proxy that watches property writes on plain objects and arrays, including nested ones, and schedules a re-render when something the template used changes. - Re-render occurs only if the template actually read the changed property during its last render.
- Rendering is batched in a microtask, so several mutations cause one render.
Advanced / deep dive: @track observes only plain objects and arrays. Class instances, Date, Map, Set and DOM nodes are not observed deeply, so mutate-and-reassign is required. Many teams avoid @track entirely by using immutable updates: this.items = [...this.items, newItem] or this.record = { ...this.record, Name: 'x' }. Immutable patterns also play well with data from @wire, which is frozen (read-only), so mutating it throws in strict mode; you must clone first. Tracked proxies add overhead on large structures, and the proxy is not the original object (identity checks and JSON.stringify are fine, but passing the proxy to a third-party library may misbehave, so use JSON.parse(JSON.stringify(x)) or a structured clone). Properties decorated with are not deeply reactive either; the parent owns the value and the child must not mutate it.