Sub topic 8
Why a child must not change its @api properties
This chapter assumes you know how a parent passes values to a child with @api, and that reassigning a field makes a component rerender. It explains why a child component should treat its own @api properties as read-only, what the engine does when you break that rule, and what to do instead.
The rule
A property marked @api is owned by the component that declares it only in the sense that the child defines its name and type. The value belongs to the parent that sets it in its template. The child reads the value and renders it. It does not write back to it.
Salesforce's documentation states this as a rule: a component that declares a public property must not change that property's value, except to set a default in the field initializer. If the child needs to report a change, it tells the parent through an event. The parent then decides whether to update its own field.
This is one-way data flow. Data goes down from parent to child through properties. Requests for change go up from child to parent through events.
What goes wrong when a child writes to an @api property
Two different failures exist, depending on the type of the value.
Primitive values: silent drift
Consider a child that changes a primitive @api property itself.
import { LightningElement, api } from 'lwc';
export default class BadQuantity extends LightningElement {
@api value = 1;
handleAdd() {
// Anti-pattern: the child writes to its own public property.
this.value += 1;
}
}The engine often does not throw here. The child rerenders and shows the new number, so the code looks correct in a quick test. The problem is that the parent still holds the old value.
<template>
<c-bad-quantity value={quantity}></c-bad-quantity>
<p>Parent thinks the quantity is {quantity}</p>
</template>If the parent's quantity is 1 and the child changes its own value to 2, the page now shows two sources of truth. The paragraph still says 1. The parent only pushes a value into the child when the parent's own value changes. If quantity stays at 1, the child keeps showing 2. If quantity later changes to a new value, the child's number is overwritten and the user's click is lost. Which of these happens depends on timing and on what the parent does next, which makes the bug hard to reproduce.
Objects and arrays: an error
When the parent passes an object or an array, the engine hands the child a read-only view of it. The child can read the properties, but writing to them fails.
import { LightningElement, api } from 'lwc';
export default class BadProfile extends LightningElement {
@api profile;
rename() {
// Throws an "Invalid mutation" error in the browser console.
this.profile.name = 'Grace';
}
}The exact wording of the message varies between releases. It says the object is read-only and the mutation is invalid. The failure is intentional. The object belongs to the parent, and the engine stops the child from changing the parent's data behind its back.
The same applies to array methods such as push, splice, and sort on an array received through @api. sort is easy to miss because it sorts in place. Copy first, as shown in the next section.
const sorted = [...this.items].sort((a, b) => a.rank - b.rank);A table of what each action does:
| Child action on an @api value | Result |
|---|---|
| Read the value in the template or JS | Works, and rerenders when the parent changes it |
| Assign a new primitive to the property | Often works locally, but the parent is out of sync and the value can be overwritten later |
| Mutate a property of a received object | Error: the object is read-only |
| Call `push` or `splice` on a received array | Error: the array is read-only |
| Copy the value into a private field, then change the copy | Works, and is the supported approach |
| Dispatch an event asking the parent to change it | Works, and is the supported approach |
Pattern 1: ask the parent with an event
When the user does something that should change the value, the child dispatches a CustomEvent. The parent listens, updates its own field, and passes the new value back down.
The child:
import { LightningElement, api } from 'lwc';
export default class QuantityPicker extends LightningElement {
@api value = 1;
handleAdd() {
this.dispatchEvent(
new CustomEvent('quantitychange', {
detail: { value: this.value + 1 }
})
);
}
}<template>
<lightning-button label="Add one" onclick={handleAdd}></lightning-button>
<p>Quantity: {value}</p>
</template>The parent:
<template>
<c-quantity-picker
value={quantity}
onquantitychange={handleQuantityChange}
></c-quantity-picker>
<p>Total items: {quantity}</p>
</template>import { LightningElement } from 'lwc';
export default class CartPage extends LightningElement {
quantity = 1;
handleQuantityChange(event) {
this.quantity = event.detail.value;
}
}Follow the flow of one click. The child does not change value. It dispatches quantitychange with the requested number. The parent's handler assigns this.quantity, which is a reassignment of a reactive field, so the parent rerenders. During that rerender, the parent sets value on the child to the new number, and the child rerenders. There is one source of truth, and both paragraphs agree.
Two details matter:
- Event names should be lowercase, with no spaces or hyphens. The parent listens with
onplus that name, soquantitychangebecomesonquantitychange. - The
detailshould carry plain data. Passing a reference to an object the child also uses invites the same read-only problems from the other direction.
Because the parent owns the decision, it can also refuse. A parent could clamp the quantity to a maximum of ten. The child would then keep showing the clamped value, because it only shows what it is given.
Pattern 2: copy into a private field
Sometimes the child really does need local state that starts from the parent's value and then diverges, for example an edit form that the user may cancel. In that case the child keeps its own copy in a plain field and edits the copy.
import { LightningElement, api } from 'lwc';
export default class ProfileEditor extends LightningElement {
draft = { name: '', city: '' };
_profile;
@api
get profile() {
return this._profile;
}
set profile(value) {
this._profile = value;
// Copy so the child can edit without touching the parent's object.
this.draft = { ...value };
}
handleNameChange(event) {
this.draft = { ...this.draft, name: event.target.value };
}
handleSave() {
this.dispatchEvent(
new CustomEvent('save', { detail: { ...this.draft } })
);
}
}<template>
<lightning-input
label="Name"
value={draft.name}
onchange={handleNameChange}
></lightning-input>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>The setter runs each time the parent assigns profile. It stores the incoming object untouched in _profile and copies it into draft. The child edits draft only. When the user saves, the child sends the copy up in an event, and the parent decides whether to accept it.
The copy made with { ...value } is shallow. Top-level properties are copied, but a nested object inside it is still the parent's read-only object. If your data has nesting, copy the levels you plan to edit, or build the copy with a helper that does a deep copy. JSON.parse(JSON.stringify(value)) works for plain data, but it drops values such as undefined and functions and turns dates into strings.
The setter also resets the draft whenever the parent assigns a new value. If the parent rerenders and passes a new object reference while the user is typing, their edits are lost. Keep this in mind if the parent's data refreshes often.
Setting defaults is allowed
The one allowed assignment is the initial value in the field declaration.
import { LightningElement, api } from 'lwc';
export default class InfoCard extends LightningElement {
@api heading = 'Untitled';
@api expanded = false;
}This sets the value that applies when the parent does not supply one. After that, the value belongs to the parent. A default of true for a boolean @api property is a trap. A parent cannot turn it off using only an attribute in HTML, because writing the attribute name alone sets it to true. Start boolean public properties at false.
Why the design works this way
Three reasons support the rule, and they are worth knowing so the rule does not feel arbitrary.
- Predictability. If both parent and child can write the same value, you have to trace two places to find out why the screen shows what it does. With one-way flow, you trace upward through event handlers to the one field that owns the data.
- Shared references. An object handed to a child is the same object the parent holds. A child that mutates it changes the parent's state without the parent's reactivity noticing, unless the parent used
@track. The read-only view turns that silent corruption into a visible error. - Reuse. A child that only displays what it receives and reports what the user did can be dropped into any parent. A child that writes to its inputs depends on how each parent reacts.
Checking your own components
When you review a component, search its JavaScript for each @api property name and look at every assignment to this.thatName outside the field declaration and a setter. Each hit is either a bug or a case for a private copy. Also search for in-place array methods applied to @api arrays.
Exercise
A child component has @api items, an array supplied by its parent. A button in the child calls this.items.push({ id: 3 }). What happens, why, and how would you fix it so the new item appears in both components?
Show answer
The push fails with a read-only mutation error, because the engine gives the child a read-only view of the parent's array. The fix is to leave the child's array alone and dispatch a custom event, for example additem, with the new item in detail. The parent's handler reassigns its own field with a new array, such as this.items = [...this.items, event.detail]. That reassignment rerenders the parent, passes the new array down through @api items, and the child rerenders with the new item.
Exercise
A child has @api label = 'Start' and a button handler that sets this.label = 'Stop'. The parent template has <c-toggle label={buttonText}></c-toggle>, and buttonText never changes. The child shows "Stop", and the parent still has "Start". Name the problem and the supported way to make the label change.
Show answer
The child has written to a public property that the parent owns, so the child and the parent now hold different values. The supported approach is for the child to dispatch an event when the button is clicked. The parent then reassigns buttonText in its handler, and the new value flows down to the child's label. If the label is purely internal state, make it a plain private field in the child instead of an @api property.