Sub topic 11
Choosing the right tool
This chapter assumes you know how an LWC component is laid out (HTML, JS, and meta files). It also assumes you are comfortable with JavaScript classes and spread syntax, and that you know the difference between a primitive value and an object reference. It builds on the earlier chapters about reactive fields, reassignment versus mutation, @track, and @api. Its job is to turn those pieces into a decision you can make quickly.
The three options
Every piece of state in a component falls into one of three groups.
| Option | Declared as | Who can see it | What triggers a rerender |
|---|---|---|---|
| Plain field | `count = 0;` | Only this component | Reassigning the field, when the template reads it |
| Tracked field | `@track profile = {...};` | Only this component | Reassigning the field, or changing a property inside the plain object or array it holds |
| Public property | `@api heading;` | This component and its parent | Reassigning from the parent. The child must not reassign it |
A fourth option, the public method (@api on a method), is not state. It lets a parent call into the child. It is covered in its own section below.
Two facts from earlier chapters carry most of the weight here:
- Every class field is reactive. If the template reads a field and your code reassigns it, the component rerenders. You do not need a decorator for that.
@trackdoes not make a field reactive. It makes changes inside the field's object or array visible.@apidoes not add reactivity either. It adds visibility to the parent.
A decision procedure
Work through these questions in order. Stop at the first one that applies.
- Does a parent component need to set this value, or call this behavior? If yes, use
@api. Use a property for data and a method for an action. - Is the value only used inside this component? If yes, start with a plain field.
- Is the value an object or array, and is it easier to change a property or element in place than to build a new copy? If yes, consider
@track. If you can reassign instead, prefer that. - Is the value derived from other fields? If yes, use a getter instead of storing a second copy.
The diagram shows the same flow.
Plain fields are the default
For primitives, a plain field is the right answer. Strings, numbers, booleans, null, and undefined change only by reassignment, so the framework always sees the change.
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>Plain fields also work for objects and arrays when you replace the whole value. Spread syntax makes this short:
import { LightningElement } from 'lwc';
export default class ProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile = { ...this.profile, name: 'Grace' };
}
}Here the field gets a new object, so the component rerenders with no decorator. This approach is the one to reach for first. It has one more benefit: because each update produces a new object, you can compare old and new values by reference if you ever need to.
When @track earns its place
Use @track when code changes a property of an object, or an element of an array, in place, and the template reads that property or element.
import { LightningElement, track } from 'lwc';
export default class TrackedProfile extends LightningElement {
@track profile = { name: 'Ada', city: 'London' };
rename() {
this.profile.name = 'Grace';
}
}Without @track, this.profile.name = 'Grace' would change the data but leave the screen stale. The field profile was not reassigned, and the framework only watches the field itself.
Good reasons to choose @track:
- The object has many properties that different handlers update independently, and rebuilding it each time would be noisy.
- You are editing a list of rows in place, for example toggling a
selectedflag on one row. - You are porting older code that mutates state, and a full rewrite is not in scope.
Reasons to avoid it:
- A single reassignment would do the job. Spread syntax is usually one line.
- The value is a primitive.
@trackhas no effect on primitives. - The value is not a plain object or array.
@trackobserves plain objects and arrays only. ADate,Map,Set, or class instance is not observed property by property. Changing its internals does not rerender, so reassign the field instead.
A worked comparison
Suppose you keep a list of tasks and let the user tick each one off. Here are the two ways to write the toggle.
With reassignment, no decorator:
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = [
{ id: 1, label: 'Write tests', done: false },
{ id: 2, label: 'Review PR', done: false }
];
handleToggle(event) {
const id = Number(event.target.dataset.id);
this.tasks = this.tasks.map((task) =>
task.id === id ? { ...task, done: !task.done } : task
);
}
}With @track, mutating in place:
import { LightningElement, track } from 'lwc';
export default class TrackedTaskList extends LightningElement {
@track tasks = [
{ id: 1, label: 'Write tests', done: false },
{ id: 2, label: 'Review PR', done: false }
];
handleToggle(event) {
const id = Number(event.target.dataset.id);
const task = this.tasks.find((t) => t.id === id);
if (task) {
task.done = !task.done;
}
}
}Both work. The first needs no decorator and always produces a fresh array. The second is shorter to write and reads naturally, but it depends on @track being present. If someone later deletes the decorator during a cleanup, the screen silently stops updating. That fragility is the main cost of @track.
When @api is required
Use @api when something must cross the component boundary. The decorator is the component's public contract. Anything without it is private, and the parent cannot reach it.
Public properties
A public property is a field the parent can set from its template.
import { LightningElement, api } from 'lwc';
export default class InfoCard extends LightningElement {
@api heading;
@api expanded = false;
}<template>
<c-info-card heading="Release notes" expanded></c-info-card>
</template>The parent writes the name in kebab-case (heading, expanded, and for a name like maxItems, max-items). The child declares it in camelCase.
Remember the data-flow rule: the parent owns the value, and the child must treat it as read-only. If the child needs a modified version, it should keep its own private copy or compute a derived value. If the child needs to ask for a change, it should dispatch an event and let the parent decide.
Getters and setters
Choose an accessor pair when the incoming value needs cleaning or when a change should cause side effects. Put @api on one of the pair, not both. By convention it goes on the getter.
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);
}
}The setter coerces any input to a number and falls back to 0. The template reads formatted, which is a plain getter that derives its result from the private field. The private field _amount is reactive because it is a field, so the template updates when the setter runs.
Public methods
Use an @api method when the parent needs to do something in the child, rather than hand it data. Focusing an input, resetting a form, and starting an animation are typical cases.
import { LightningElement, api } from 'lwc';
export default class SearchBox extends LightningElement {
@api
focusInput() {
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}import { LightningElement } from 'lwc';
export default class SearchPage extends LightningElement {
handleReset() {
const box = this.template.querySelector('c-search-box');
if (box) {
box.focusInput();
}
}
}Prefer a property when the parent is describing state ("the box is disabled") and a method when it is issuing a command ("focus now"). A command expressed as a property tends to need awkward tricks, such as toggling a boolean to fire an effect.
Comparing the three on a single requirement
The same requirement can sometimes be solved with different tools. These examples show how the requirement picks the tool.
| Requirement | Best fit | Why |
|---|---|---|
| Show how many times a button was clicked | Plain field | A primitive, private, changed by reassignment |
| Replace a user's profile after a save | Plain field, reassigned | Whole value is replaced, so no observation of inner changes is needed |
| Edit one row's `done` flag inside a list in place | `@track` or `map` reassignment | In-place mutation needs `@track`. Reassigning avoids it |
| Let a parent pass in a title | `@api` property | Crosses the component boundary |
| Clean up a value the parent passes in | `@api` getter and setter | The setter is the place to normalize |
| Let a parent move focus into the child | `@api` method | An action, not state |
| Show a full name made from first and last name | Getter, no decorator | Derived data should not be stored twice |
Combining decorators
You cannot put @api and @track on the same field. Both are decorators on one field, and LWC rejects the combination. A field that is @api is already reactive when the parent reassigns it. A parent that passes in an object can still be observed by the child as read-only data.
If a child needs to change data it received, copy it into a private field and work on the copy:
import { LightningElement, api } from 'lwc';
export default class EditableProfile extends LightningElement {
_profile;
draft;
@api
get profile() {
return this._profile;
}
set profile(value) {
this._profile = value;
this.draft = { ...value };
}
handleNameChange(event) {
this.draft = { ...this.draft, name: event.target.value };
}
}The parent's object is never mutated. The child edits draft, which is a plain field replaced on every change. To publish the result, the child would dispatch a custom event carrying draft, and the parent would decide whether to accept it.
Common mistakes when choosing
- Adding
@trackto everything. It is not harmful on an object, but it hides whether the code relies on in-place mutation. Add it only where you mutate. - Adding
@trackto a primitive. It does nothing. - Marking private state
@api. This widens the public contract. Any field with@apiis something a parent may start depending on, and renaming it later becomes a breaking change. - Assigning to an
@apiproperty inside the child. The framework treats public properties as owned by the parent. Writing to them in the child can log errors in development and gets overwritten the next time the parent sets the value. - Mutating an object passed through
@api. The child might not be able to observe the change reliably, and the parent's data changes without the parent knowing. Copy first. - Expecting
@trackto observe aDateorMap. Reassign those values instead. - Storing derived values in fields. A stored full name goes stale when only the first name changes. Use a getter.
Exercises
Exercise
A component keeps selectedIds as an array of numbers. A click handler runs this.selectedIds.push(id), and the template shows {selectedIds.length}, but the count never changes. Give two fixes and say which you would choose.
Show answer
Fix one: add @track to selectedIds, so the in-place push is observed. Fix two: reassign the field with this.selectedIds = [...this.selectedIds, id];. Prefer the reassignment. It needs no decorator, it works the same way for any value, and it does not break if the decorator is later removed.
Exercise
A parent passes a config object into a child through an @api property. The child wants to let the user change config.pageSize in a form. How should the child handle this, and why not write to config directly?
Show answer
The child should copy the object into a private field, for example this.draft = { ...value } inside the setter, and update the copy by reassignment. Public properties are owned by the parent, so the child must treat them as read-only. Mutating the parent's object changes data the parent does not know about, and the parent's next assignment can overwrite the child's change. To send the result back, the child dispatches a custom event and the parent decides whether to update config.
Exercise
For each requirement, name the best tool: (a) a boolean that tracks whether a dropdown is open, (b) a method that lets a parent clear a child's search text, (c) a label the parent sets on the child, (d) a fullName shown from firstName and lastName.
Show answer
(a) A plain field, because it is a private primitive. (b) An @api method, because it is a command from the parent. (c) An @api property, because the value crosses the component boundary. (d) A plain getter that joins the two names, because it is derived and should not be stored.