Sub topic 7
One-way data flow: the child does not change what it receives
This chapter assumes you can write a basic Lightning web component and that you have already used @api to expose a property, as covered in earlier chapters. You should also be comfortable with spread syntax and Array.prototype.map.
The rule
Data in Lightning web components moves in one direction. A parent owns a value and passes it down to a child through a public property. The child reads that value but does not change it. If the child needs the value to change, it asks the parent by sending an event. The parent then updates its own data and passes the new value down again.
This is called one-way data flow. It gives every value a single owner, so when something looks wrong you know which component to inspect.
What "read-only" means in practice
The rule has two layers. The first is a convention that applies to every value. The second is enforced by the engine for objects and arrays.
| Value passed from the parent | What the child can do | What happens if the child mutates it |
|---|---|---|
| String, number, boolean | Read it, display it, derive new values from it | Unsupported. The parent's data does not change, and the parent's next update overwrites the child's value. |
| Object | Read its fields, copy it | The assignment is rejected and the console reports an "Invalid mutation" error. |
| Array | Read items, iterate, copy it | `push`, `splice`, in-place `sort` and similar changes are rejected. |
For objects and arrays, the child does not receive the parent's actual object. It receives a read-only wrapper around it. Reading works as usual. Writing is blocked, and the block applies at every depth of the structure.
The wrapper exists because shared mutable data makes bugs hard to trace. If a child could edit an array that its parent also uses, a change in one component would silently alter another. The parent's template would not necessarily re-render, and the two components could disagree about the current state.
A failing example
Here is a child that receives a task object. The handleToggle method tries to flip done directly.
// taskItem.js (child, incorrect)
import { LightningElement, api } from 'lwc';
export default class TaskItem extends LightningElement {
@api task;
handleToggle() {
// Rejected: this.task is a read-only view of the parent's object.
this.task.done = !this.task.done;
}
}When the user clicks the button, the assignment is blocked and you see an error similar to this in the browser console:
Invalid mutation: Cannot set "done" on "[object Object]". "[object Object]" is read-only.The error message tells you the cause: the child is writing to a value it does not own.
The correct pattern: ask the parent
The child leaves the task untouched and dispatches a custom event that says what happened. The parent owns the data, so the parent changes it.
// taskItem.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskItem extends LightningElement {
@api task;
handleToggle() {
this.dispatchEvent(
new CustomEvent('toggle', { detail: { id: this.task.id } })
);
}
}<!-- taskItem.html (child) -->
<template>
<li>
<span>{task.name}</span>
<button onclick={handleToggle}>
{task.done}
</button>
</li>
</template>The parent listens for the event, builds a new array with the changed task, and assigns it to its own field.
// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
tasks = [
{ id: 't1', name: 'Write documentation', done: false },
{ id: 't2', name: 'Review pull request', done: false }
];
handleToggle(event) {
const id = event.detail.id;
this.tasks = this.tasks.map((task) =>
task.id === id ? { ...task, done: !task.done } : task
);
}
}<!-- taskBoard.html (parent) -->
<template>
<ul>
<template for:each={tasks} for:item="task">
<c-task-item
key={task.id}
task={task}
ontoggle={handleToggle}>
</c-task-item>
</template>
</ul>
</template>The full cycle runs like this:
- The user clicks the button in the child.
- The child dispatches
togglewith the task id. - The parent's
handleToggleruns and replacesthis.taskswith a new array. The changed task is a new object, made with spread syntax. - The parent re-renders, and the child receives the updated
taskproperty.
Notice that the parent replaces the array and the changed object instead of editing the existing ones. The engine detects a change when a field is assigned a new value. Replacing the value keeps the update visible to the framework. It also matches how the read-only wrapper treats the data.
Copying data you need to change
Sometimes the child has a legitimate reason to reorder or filter the data it received, for example a sortable list that is purely a display concern. In that case the child makes its own copy, as in the setter pattern shown earlier in this series.
// taskList.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
get tasks() {
return this._tasks;
}
set tasks(value) {
this._tasks = Array.isArray(value) ? [...value] : [];
}
handleSortByName() {
this._tasks = [...this._tasks].sort((a, b) =>
a.name.localeCompare(b.name)
);
}
}The setter stores a new array in the private field _tasks. The child owns that array, so it may replace it whenever it likes. The parent's array is never touched.
A copy is shallow
The spread operator copies one level. In the example above, the new array holds the same task objects as the parent's array, and those objects are still read-only. Reordering the copy is allowed. Changing a task's field is not:
// Inside TaskList
handleMarkFirstDone() {
// Still rejected: the first item is the parent's read-only object.
this._tasks[0].done = true;
}To change an item, replace it with a copy:
handleMarkFirstDone() {
this._tasks = this._tasks.map((task, index) =>
index === 0 ? { ...task, done: true } : task
);
}This updates what the child displays. It does not change the parent's data. If the parent also needs to know about the change, the child must dispatch an event as well. Otherwise the two components show different states, and the child's copy is discarded the next time the parent assigns a new tasks value.
Where a child may assign its own public property
The rule is about values the child receives. A child can give a public property a default value in its class body, such as @api priority = 'normal';. It can also assign private fields freely. The restriction is on writing to a public property from inside the component after an owner has supplied it. If you find yourself wanting to do that, one of these is usually the better design:
- Store the incoming value in a private field through a setter, then change the private field.
- Use a getter to compute a derived value from the property and display that.
- Dispatch an event so the owner changes the source.
A getter is often the simplest fix for display needs:
// taskItem.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskItem extends LightningElement {
@api task;
get statusLabel() {
return this.task && this.task.done ? 'Done' : 'Open';
}
}The template uses {statusLabel}. The child never changes task, and the label stays correct whenever the parent passes a new object.
Debugging checklist
When a child does not behave as you expect, check these in order:
- Does the console show "Invalid mutation"? If so, find the line in the child that writes to a received object or array.
- Does the child's display change but revert later? The child probably edited its own copy or a primitive, and the parent's next update overwrote it.
- Did the parent change data but the child did not update? Check that the parent assigned a new value to the field instead of editing the existing object in place.
- Does the parent never learn about a user action? Check that the child dispatches an event and that the parent's markup has the matching
onhandler, with a lowercase event name.
Exercise
A child component has @api items and a button handler that calls this.items.push({ id: 'new' }). The console reports an "Invalid mutation" error. Give two valid ways to fix the design, and say when you would pick each.
Show answer
First, if the new item matters only for the child's display, store a copy in a private field through a setter (this._items = [...value]) and push to the copy, for example this._items = [...this._items, { id: 'new' }]. The parent never sees the change. Second, if the parent owns the list and must know about the new item, dispatch a custom event such as additem with the item in detail. The parent then assigns a new array, for example this.items = [...this.items, event.detail], and passes it back down. Pick the event when the change is real application data. Pick the local copy when the change is a display detail.
Exercise
A child receives @api task and uses a spread copy of the parent's array in a setter. The child then runs this._tasks[0].done = true. Why does this still fail, and how do you change the first task correctly?
Show answer
The spread copy is shallow. The new array is a separate list, but its items are the same task objects, which are still read-only views of the parent's data. Assigning to a field of an item is rejected. Replace the item with a copy instead, for example this._tasks = this._tasks.map((t, i) => i === 0 ? { ...t, done: true } : t).