LearnFrenzy
Sign in Take a free test

Templates and Reactivity · Lesson 5 of 25

LWC Data Binding, Reactivity and Getters

6 min read Updated Nov 8, 2026 Saurabh Samir

Data binding connects your JavaScript class to the template: a field changes, and the screen updates. In LWC this works one way – from JavaScript to HTML – and you send user input back yourself with event handlers. Understanding exactly which changes LWC notices is the key to avoiding the classic "my component doesn't update" bug.

In this lesson

  • Binding fields and getters in templates
  • Handling input: the event-to-field pattern
  • What is reactive – and the object/array trap
  • When @track is still needed

Fields, getters and input

<!-- discountCalculator.html -->
<template>
    <lightning-card title="Discount calculator">
        <div class="slds-p-horizontal_small">
            <lightning-input type="number" label="List price" value={price} onchange={handlePriceChange}></lightning-input>
            <lightning-input type="number" label="Discount %" value={discount} onchange={handleDiscountChange}></lightning-input>
            <p>You save: {savings}</p>
            <p>Final price: {finalPrice}</p>
            <p class={warningClass}>{approvalText}</p>
        </div>
    </lightning-card>
</template>
// discountCalculator.js
import { LightningElement } from 'lwc';

const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

export default class DiscountCalculator extends LightningElement {
    price = 1000;
    discount = 10;

    handlePriceChange(event) {
        this.price = Number(event.detail.value);       // input → field
    }

    handleDiscountChange(event) {
        this.discount = Number(event.detail.value);
    }

    // getters: computed from fields, recalculated whenever the template renders
    get savings() {
        return money.format((this.price * this.discount) / 100);
    }

    get finalPrice() {
        return money.format(this.price - (this.price * this.discount) / 100);
    }

    get needsApproval() {
        return this.discount > 20;
    }

    get approvalText() {
        return this.needsApproval ? 'Manager approval required' : 'Within your discount limit';
    }

    get warningClass() {
        return this.needsApproval ? 'slds-text-color_error' : 'slds-text-color_success';
    }
}

Result

▌Discount calculator
List price [1000] Discount % [10]
You save: $100.00
Final price: $900.00
Within your discount limit

› clear List price and type “2500”
▌Discount calculator
List price [2500] Discount % [10]
You save: $250.00
Final price: $2,250.00
Within your discount limit

› clear Discount % and type “25”
▌Discount calculator
List price [2500] Discount % [25]
You save: $625.00
Final price: $1,875.00
Manager approval required

One-way binding with an event

  1. Rendervalue={discount} puts the field's value into the input
  2. User typeslightning-input fires change with event.detail.value
  3. Handlerthis.discount = … assigns the field
  4. Re-renderthe input and every getter that reads discount update
  • Templates can only reference properties and getters – no expressions, no function calls. Put logic in getters; it keeps the template readable and the logic testable.
  • Getters re-run on every render, so keep them cheap: no Apex calls, no heavy loops over thousands of rows.
  • Getters work for attributes too: class={warningClass} switches SLDS classes.

What LWC tracks

Every class field is reactive – but shallowly. LWC re-renders when you assign a new value to a field (it compares old and new with ===). Changing something inside an object or array that's still the same object isn't noticed – unless the field is decorated with @track:

<!-- trackingDemo.html -->
<template>
    <p>Plain field: {itemsText}</p>
    <p>@track field: {trackedText}</p>
    <lightning-button label="Push to plain field" onclick={pushPlain}></lightning-button>
    <lightning-button label="Push to @track field" onclick={pushTracked}></lightning-button>
    <lightning-button label="Assign a new array" onclick={assignNew}></lightning-button>
</template>
// trackingDemo.js
import { LightningElement, track } from 'lwc';

export default class TrackingDemo extends LightningElement {
    items = ['Laptop'];                  // reactive to reassignment only
    @track trackedItems = ['Laptop'];    // also observes changes inside the array

    get itemsText() {
        return this.items.join(', ');
    }
    get trackedText() {
        return this.trackedItems.join(', ');
    }

    pushPlain() {
        this.items.push('Mouse');                 // ✗ same array: no re-render
    }

    pushTracked() {
        this.trackedItems.push('Mouse');          // ✓ @track observes the mutation
    }

    assignNew() {
        this.items = [...this.items, 'Monitor'];  // ✓ new value: always re-renders
    }
}

Result

Plain field: Laptop
@track field: Laptop
[Push to plain field] [Push to @track field] [Assign a new array]

› click “Push to plain field”
Plain field: Laptop
@track field: Laptop
[Push to plain field] [Push to @track field] [Assign a new array]

› click “Push to @track field”
Plain field: Laptop, Mouse
@track field: Laptop, Mouse
[Push to plain field] [Push to @track field] [Assign a new array]

› click “Assign a new array”
Plain field: Laptop, Mouse, Monitor
@track field: Laptop, Mouse
[Push to plain field] [Push to @track field] [Assign a new array]

Read the panel carefully:

  • Pushing to the plain field changed the array, but the screen didn't update – the field still holds the same array.
  • The @track push re-rendered, because @track wraps plain objects and arrays in a proxy that watches their contents. Notice that the plain field suddenly showed "Mouse" too: the earlier, silent mutation only appeared because another change happened to trigger a render. Bugs like this appear and disappear depending on unrelated clicks.
  • Assigning a new array always re-renders – the reliable approach.

When to use @track

All fields have been reactive since Spring '20, so you only need @track to observe in-place changes to a plain object or array. Most experienced LWC developers avoid needing it by always assigning new values: this.items = [...this.items, 'Mouse'], this.filters = { ...this.filters, stage: 'Won' }. That style works with or without @track, works for data that came frozen from Salesforce, and makes changes easy to follow. Note that even @track doesn't observe Date, Map, Set or class instances – assign a new one.

Data from Salesforce is read-only

Records delivered by @wire (Lightning Data Service or Apex) are frozen. Mutating them throws an error. Copy first: this.rows = data.map((r) => ({ ...r, selected: false })).

Practice

Try it yourself

  1. Build a character counter for a tweet-style text area: show "N/280" and "Too long" when it exceeds 280.

    Show solution
    <!-- postComposer.html -->
    <template>
        <lightning-textarea label="Post" value={text} onchange={handleChange}></lightning-textarea>
        <p>{counter}</p>
    </template>
    // postComposer.js
    import { LightningElement } from 'lwc';
    
    const MAX = 280;
    
    export default class PostComposer extends LightningElement {
        text = '';
    
        handleChange(event) {
            this.text = event.detail.value;
        }
    
        get counter() {
            const n = this.text.length;
            return n > MAX ? `${n}/${MAX} – Too long` : `${n}/${MAX}`;
        }
    }

    Result

    Post []
    0/280
    
    › type “Deploying LWC on Friday!” into Post
    Post [Deploying LWC on Friday!]
    24/280

Quick check

Is data binding in LWC one-way or two-way?

One-way: JavaScript to template. User input comes back through event handlers.

Why doesn't this.items.push(x) re-render?

Fields are tracked shallowly – the field still holds the same array. Assign a new array, or decorate the field with @track.

When do you need @track in modern LWC?

Only to observe in-place changes to a plain object or array; assigning new values avoids the need.

Summary

  • Templates bind fields and getters; compute everything else in getters.
  • Send input back with change handlers that assign fields.
  • Fields are reactive to reassignment; mutate in place only with @track – or, better, assign new objects and arrays.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links