Sub topic 12
Common pitfalls and how to avoid them
This chapter collects the mistakes that come up most often with reactive fields, @track, and @api. It assumes you know the earlier material: every field is reactive, reassignment triggers a rerender, @track observes changes inside plain objects and arrays, and @api exposes public properties and methods. You should also be comfortable with spread syntax and with the difference between a value and a reference.
Each pitfall below gives the symptom, the cause, and the fix.
Pitfall 1: Mutating an object or array without `@track`
Symptom: The data changes (you can see it in the debugger), but the screen does not.
Cause: A plain field triggers a rerender when its value is replaced. Calling push on an array or setting a property on an object leaves the field pointing at the same reference, so the framework sees no change.
import { LightningElement } from 'lwc';
export default class TodoList extends LightningElement {
items = ['Write tests'];
addBroken() {
// Same array, so no rerender.
this.items.push('Ship');
}
add() {
// New array, so the template refreshes.
this.items = [...this.items, 'Ship'];
}
}<template>
<lightning-button label="Add" onclick={add}></lightning-button>
<ul>
<template for:each={items} for:item="item">
<li key={item}>{item}</li>
</template>
</ul>
</template>Fix: Build a new value and assign it. Use spread, map, filter, or slice for arrays, and { ...obj, key: value } for objects. This is the default approach. Reach for @track only when reassignment is genuinely awkward.
Pitfall 2: Reaching for `@track` when you don't need it
Symptom: Every object or array field carries @track, and nobody remembers why.
Cause: Older code and older tutorials needed @track on every field that should rerender. That requirement is gone. Plain fields are reactive on their own.
@track on a primitive such as a number, string, or boolean does nothing useful. It also hides the real rule from the next reader. Put it on a field only when your code mutates that field's nested properties in place and you have chosen not to reassign.
import { LightningElement, track } from 'lwc';
export default class TrackedProfile extends LightningElement {
@track profile = { name: 'Ada', city: 'London' };
rename() {
this.profile.name = 'Grace';
}
}Fix: Start with a plain field. Add @track when you can name the nested mutation it supports.
Pitfall 3: Expecting `@track` to observe everything
Symptom: A field has @track, yet some changes still don't update the template.
Cause: @track observes plain objects and arrays, including those nested inside them. It does not observe other kinds of values:
- Instances of your own classes, whose internal state changes are not watched.
- Built-in objects such as
Date,Map, andSet. - Changes you make to a value after you have copied it somewhere else. Tracking follows the tracked reference, not copies.
import { LightningElement, track } from 'lwc';
class Cart {
total = 0;
}
export default class CartView extends LightningElement {
@track cart = new Cart();
addBroken() {
// Cart is a class instance, so this change is not observed.
this.cart.total += 10;
}
add() {
const next = new Cart();
next.total = this.cart.total + 10;
this.cart = next;
}
}Fix: For anything other than plain objects and arrays, replace the whole value. For a Date, create a new Date. For a Map, build a new Map from the old one.
Pitfall 4: Fields that the template never reads
Symptom: You change a field and nothing visibly happens, even though reassignment is correct.
Cause: A rerender only matters if the template depends on the value. A field used only in JavaScript, such as a timer id or a cached lookup, produces no visible change. This is normal and often what you want.
The reverse case also surprises people. A getter is reactive when the template reads the getter and the getter reads reactive fields. Nothing else needs to be declared.
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
firstName = 'Ada';
lastName = 'Lovelace';
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
changeLast() {
this.lastName = 'Byron';
}
}<template>
<p>{fullName}</p>
<lightning-button label="Change" onclick={changeLast}></lightning-button>
</template>Fix: If you expect the screen to change, check that the template, directly or through a getter, reads the field you are assigning. Don't call a rerender manually. Assigning a new value is enough.
Pitfall 5: Changing an `@api` property inside the child
Symptom: A child sets this.value = ... on its own public property. The display flickers, reverts, or the console shows an error.
Cause: Data flows one way, from parent to child. The parent owns the value. If the child overwrites it, the next time the parent sets the property the child's change is lost. The parent and child can then disagree about the current value. When the value is an object, the framework hands the child a read-only version of it, so changing a nested property can throw an error.
import { LightningElement, api } from 'lwc';
export default class QuantityPicker extends LightningElement {
@api value = 1;
handleIncrease() {
// Ask the parent to change it. Do not write to this.value.
this.dispatchEvent(
new CustomEvent('change', { detail: { value: this.value + 1 } })
);
}
}<template>
<lightning-button label="+" onclick={handleIncrease}></lightning-button>
<span>{value}</span>
</template>The parent listens and stores the new value in its own field:
<template>
<c-quantity-picker value={qty} onchange={handleChange}></c-quantity-picker>
</template>import { LightningElement } from 'lwc';
export default class OrderLine extends LightningElement {
qty = 1;
handleChange(event) {
this.qty = event.detail.value;
}
}If the child needs a value it can change freely, copy the incoming value into a private field and edit that copy.
Fix: The child reports what happened with an event, and the parent decides what to store.
Pitfall 6: Modifying data you did not create
Symptom: An error such as "Cannot set property ... of #<Object> which has only a getter" or a message about a read-only object.
Cause: Objects passed through @api are read-only inside the child. Records and results delivered by @wire are also read-only. Writing to either fails.
import { LightningElement, api } from 'lwc';
export default class AccountEditor extends LightningElement {
_account;
draft;
@api
get account() {
return this._account;
}
set account(value) {
this._account = value;
// Copy first. The incoming object is read-only.
this.draft = { ...value };
}
handleName(event) {
this.draft = { ...this.draft, Name: event.target.value };
}
}The spread copy is shallow. If the object has nested objects or arrays that you intend to change, copy those levels too.
Pitfall 7: Getter and setter mistakes
Symptom: A compile error about decorating both accessors, or a setter that throws on first load.
Cause: There are two separate mistakes.
- Placing
@apion both the getter and the setter. Decorate only one of them. The decorator covers the pair. - Assuming the setter runs once, late, with a valid value. In practice the setter may run before the component is connected and before its template exists. It can also receive
undefined.
import { LightningElement, api } from 'lwc';
export default class PriceTag extends LightningElement {
_amount = 0;
@api
get amount() {
return this._amount;
}
set amount(value) {
this._amount = Number(value) || 0;
}
get formatted() {
return this._amount.toFixed(2);
}
}Fix: Keep the setter small. Normalize the value and store it. Don't query the template inside it. If the setter's result needs DOM work, do that in renderedCallback.
Pitfall 8: Boolean properties that default to `true`
Symptom: A parent writes <c-panel visible="false"> and the panel is still visible.
Cause: In a template, a bare attribute such as expanded sets the property to true. Writing visible="false" passes the string "false", which is truthy. A property that defaults to true also can't be turned off by leaving the attribute out, because absence means the default.
Fix: Make boolean public properties default to false, and name them so that true is the unusual state. Prefer @api collapsed = false over @api visible = true. If the parent needs to pass a computed value, bind it with braces, as in visible={isVisible}.
Pitfall 9: Calling a child's `@api` method too early
Symptom: TypeError: Cannot read properties of null, or the method does nothing.
Cause: this.template.querySelector returns null if the child isn't in the DOM yet. This happens in connectedCallback, or when the child sits behind an if:true that is currently false.
import { LightningElement } from 'lwc';
export default class SearchPage extends LightningElement {
handleReset() {
const box = this.template.querySelector('c-search-box');
if (box) {
box.focusInput();
}
}
}Fix: Call the method from an event handler or from renderedCallback, and check for null. Prefer passing data through properties, and use methods only for actions that are not state, such as moving focus or opening a dialog.
Pitfall 10: Illegal or confusing public property names
Symptom: A warning or build error about a property name, or an attribute that is ignored.
Cause: Public property names follow HTML conventions. A name can't start with on, because the framework reads that prefix as an event handler. It also shouldn't collide with global HTML attributes such as title or id, and it shouldn't start with data or aria. In a parent's markup, a camelCase name is written in kebab-case, so maxItems becomes max-items.
Fix: Use short, descriptive names such as heading, maxItems, or recordId. If two attributes only differ in case, rename one.
A quick triage path
When the screen doesn't update, work through these questions in order.
Summary table
| Pitfall | Quick fix |
|---|---|
| `push` or property assignment on a plain field | Reassign a new array or object |
| `@track` on primitives | Remove it |
| `@track` on class instances, `Date`, `Map`, `Set` | Replace the whole value |
| Child writes to its `@api` property | Dispatch an event, let the parent update |
| Writing to a read-only object | Copy it first |
| `@api` on both getter and setter | Decorate one only |
| Boolean `@api` defaulting to `true` | Default to `false`, rename the property |
| Method call on a missing child | Null-check, call after render |
Exercise
A component has @api selected = true;. A parent writes <c-filter selected="false">, but the filter still behaves as selected. Why does this happen, and what is the cleanest fix?
Show answer
The attribute passes the string "false", which is truthy, and a true default can't be turned off by omitting the attribute. Change the property to default to false (for example @api unselected = false or a similarly inverted name), or bind a real boolean with selected={isSelected}.
Exercise
A child component receives @api config (an object) and runs this.config.pageSize = 50 in a handler. This fails. Write the safe approach in one or two sentences.
Show answer
The object arrives read-only, so the child must not write to it. Copy it into a private field, such as this.draft = { ...this.config, pageSize: 50 }, and use that copy. If the parent needs to know about the change, dispatch an event carrying the new value.
Exercise
You have @track cart = new Cart(); where Cart is your own class. You do this.cart.total += 10; and the template stays the same. Name the cause and one fix.
Show answer
@track observes only plain objects and arrays, not class instances. Create a new Cart with the updated total and assign it to this.cart, or store the data in a plain object instead of a class instance.