Reactivity, Getters & Template Directives
How LWC reactivity works with tracked state and getters, plus the core template directives for rendering and lists.
Reactivity, getters & template directives
Reactivity is what makes a component's UI update automatically when its data changes. In LWC, any field on the class is reactive for primitive values — assign a new string or number and the template re-renders. For objects and arrays, reactivity is deeper only when you reassign the reference or use the @track decorator, so mutating a nested property in place may not re-render unless you replace the object. The practical rule: assign new values rather than mutating in place, and reach for @track when you need deep observation of an object or array.
import { LightningElement, track } from 'lwc';
export default class CartSummary extends LightningElement {
items = [
{ id: '1', name: 'Platform Licence', price: 50 },
{ id: '2', name: 'Analytics Add-on', price: 30 }
];
// A getter derives value from state and is reactive
get total() {
return this.items.reduce((sum, i) => sum + i.price, 0);
}
get hasItems() {
return this.items.length > 0;
}
}
Getters are the idiomatic way to compute derived values. Rather than storing a total you must keep in sync, expose a getter that recomputes from source state; the template calls it like a property ({total}) and it re-evaluates whenever its inputs change. Getters keep templates clean and logic testable, and they're preferred over doing computation in the markup, which LWC doesn't allow anyway — you can't call functions with arguments in the template.
<template>
<template lwc:if={hasItems}>
<ul>
<template for:each={items} for:item="line">
<li key={line.id}>{line.name} — {line.price}</li>
</template>
</ul>
<p>Total: {total}</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>
The template directives control rendering. lwc:if, lwc:elseif, and lwc:else conditionally render blocks (replacing the older if:true/if:false). for:each with for:item iterates a list, and every iterated element needs a unique key so LWC can efficiently track changes — the key must be a stable id, never the index. There's also iterator: when you need first/last flags. Master these and you can render any data-driven UI. Next we make components interactive by handling and dispatching events.