Sub topic 11
Choosing the right tool
This chapter assumes you know that every class field in a Lightning web component is reactive and that reassigning a field triggers a rerender. It also assumes you have seen @track and @api used. Here you will turn those pieces into a decision process.
Start with the plain field
A plain field is the default. It is reactive, it needs no import, and it is private to the component. Use it for any state the component owns: a counter, a selected id, a loading flag.
When the value is an object or array, you can still use a plain field. Replace the value instead of changing it:
this.profile = { ...this.profile, name: 'Grace' };
this.items = [...this.items, newItem];Reassignment changes the field's value, so the component rerenders. This also works well with the @api rules below, because you never change an object another component may be holding.
Add @track only for in-place changes
@track is for one situation. The field holds a plain object or array, and your code changes its inner properties or elements. Examples are this.draft.title = value and this.rows.push(row).
Use it when a form-style object receives many small edits and rebuilding it each time would be awkward. It does not observe everything. Class instances, Date, Map, and Set are not watched deeply. If your field holds one of those, reassign it.
Use @api for the parent boundary
@api marks the part of a component that a parent may use. A decorated field or accessor is a public property. A decorated method is a public method. The parent sets properties and calls methods. The child must not assign to its own @api properties. If the child needs to change the value, it copies it into a private field or dispatches an event so the parent can change it.
Pick the form by what the parent needs to do:
| Parent needs to | Use |
|---|---|
| Pass in a value | `@api` field |
| Pass in a value that must be checked or converted | `@api` getter and setter pair |
| Trigger an action in the child, such as focus | `@api` method |
| Nothing, the state is internal | Plain field |
Keep the public surface small. Everything you mark @api becomes a contract that parents depend on.
A combined example
This component takes its data from a parent, keeps a private selection, and edits a draft in place:
import { LightningElement, api, track } from 'lwc';
export default class TaskEditor extends LightningElement {
@api tasks = [];
selectedId;
@track draft = { title: '', notes: '' };
handleSelect(event) {
this.selectedId = event.target.dataset.id;
}
handleTitle(event) {
this.draft.title = event.target.value;
}
handleSave() {
this.dispatchEvent(
new CustomEvent('save', { detail: { ...this.draft } })
);
this.draft = { title: '', notes: '' };
}
}Each field has a different job:
tasksis owned by the parent, so it is@apiand the child only reads it.selectedIdis private state, so it is a plain field. Reassigning it is enough.draftis edited property by property, so it uses@track.- On save, the child sends a copy of the draft through an event and then reassigns the field. It does not change
tasks.
Decision flow
Common mistakes in choosing
- Marking internal state
@apijust to make it easy to test. This exposes it to every parent. - Writing to an
@apiproperty inside the child. Copy it to a private field first. - Putting
@apion both the getter and the setter. Put it on one of them. - Expecting
@trackto watch aMapor a class instance.
Exercise
A component receives a user object from its parent, shows user.name, lets the person edit a copy of the name in an input, and calls the parent back when they confirm. Which decorators or field types would you use for the incoming object, the edited copy, and the confirmation?
Show answer
Make user an @api field because the parent owns it, and do not modify it in the child. Store the edited name in a plain field such as editedName, and reassign it on every input event. Because it is a string, @track is not needed. On confirm, dispatch a CustomEvent carrying editedName so the parent can update user.