Sub topic 5
Why Props Are Read-Only
What this chapter assumes
You should know how to pass props to a function component and read them, including destructuring (covered in earlier chapters). You should also know the basics of JavaScript objects and arrays, including that const stops reassignment but not mutation. You need a running React project, for example one created with Vite.
The rule
A component must never change its own props. Props are the inputs to a component, and a component's job during rendering is to turn those inputs into JSX. React treats a component like a pure function: the same props and state should always produce the same output, and rendering should not modify anything it did not create.
// Broken: writes to the props object
function Greeting(props) {
props.name = props.name.toUpperCase();
return <h1>Hello, {props.name}!</h1>;
}In development builds, React freezes the props object with Object.freeze. Modules are strict mode by default, so the assignment above throws TypeError: Cannot assign to read only property 'name' of object. The fix is to compute a new value instead of overwriting the input.
function Greeting({ name }) {
const shout = name.toUpperCase();
return <h1>Hello, {shout}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}shout is a local variable created during this render. It is not a prop, so you are free to compute it.
The freeze is shallow
Object.freeze only protects the top level of the props object. If a prop holds an object or an array, the prop itself cannot be reassigned, but the contents of that object can still be changed. JavaScript will not stop you, and React will not warn you.
// Broken: no error is thrown, but the parent's array is changed
function SortedList({ items }) {
items.sort();
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
export default function App() {
const fruits = ['pear', 'apple', 'mango'];
return (
<div>
<SortedList items={fruits} />
<p>Original order: {fruits.join(', ')}</p>
</div>
);
}Array.prototype.sort sorts in place. The fruits array belongs to App, and SortedList has just reordered it. Because the paragraph is rendered after the list, it will print the sorted order, even though the parent never asked for that. Anything else that reads fruits now sees a different array than the one the parent created.
The fix is to copy the data before you change it.
function SortedList({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
export default function App() {
const fruits = ['pear', 'apple', 'mango'];
return (
<div>
<SortedList items={fruits} />
<p>Original order: {fruits.join(', ')}</p>
</div>
);
}Now the list shows apple, mango, pear and the paragraph shows pear, apple, mango. In current JavaScript runtimes you can also write items.toSorted(), which returns a new array.
The table below lists common array and object operations, split by whether they mutate their input.
| Mutates the original | Returns a new value instead |
|---|---|
| `push`, `pop`, `shift`, `unshift` | `[...items, x]`, `items.slice(0, -1)` |
| `splice` | `slice`, `filter` |
| `sort`, `reverse` | `[...items].sort()`, `toSorted()`, `toReversed()` |
| `obj.key = value` | `{ ...obj, key: value }` |
| `delete obj.key` | Destructure and omit: `const { key, ...rest } = obj` |
Why React insists on this
One-way data flow
Data moves down the tree: a parent passes props, and a child reads them. When a child changes a value it received, the parent's data changes without the parent knowing. Another child that got the same object now sees different data. Bugs of this kind are hard to find, because the code that changed the value is far from the code that shows the wrong result.
Rendering can happen more than once
React is free to call your component function several times for one visible update. In development, StrictMode deliberately renders every component twice to expose impure code. React may also pause, discard, or restart a render, and with concurrent features a render may never be committed to the screen. A render that mutates its inputs breaks under all of these.
Here is a component that behaves differently depending on how often React calls it.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
function Report({ log }) {
log.push('rendered Report');
return <p>Entries so far: {log.length}</p>;
}
const sharedLog = [];
function App() {
return <Report log={sharedLog} />;
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);You might expect Entries so far: 1. Under StrictMode in development, the page shows a count of 2, because React called Report twice and each call pushed an entry. In production it shows 1. The output depends on how many times React chose to render, which is exactly what a pure component must avoid.
Memoization and skipping work
React can skip re-rendering a component when its props have not changed. This is the idea behind memo, which compares props shallowly. If you mutate an array in place, its reference stays the same, so a comparison that checks "same reference?" concludes that nothing changed. The screen then shows stale data. When you create new objects and arrays instead of editing old ones, a reference check is a reliable way to detect change.
What is allowed
The rule is about props and anything you did not create. These are fine inside a component:
- Declaring local variables and changing them during the same render.
- Building a new array or object from props and returning it.
- Reassigning a destructured variable. This does not touch the props object, but it is confusing, so prefer
constand a new name. - Changing values in event handlers and effects. Those run outside rendering, so they do not break purity, but they should still change state through React, not edit props.
The next example creates and changes a local array during render. That is safe because the array did not exist before the render began.
function EvenNumbers({ numbers }) {
const evens = [];
for (const n of numbers) {
if (n % 2 === 0) {
evens.push(n);
}
}
return <p>Evens: {evens.join(', ')}</p>;
}
export default function App() {
return <EvenNumbers numbers={[1, 2, 3, 4, 5, 6]} />;
}React's term for this is local mutation. Each call to EvenNumbers gets its own fresh evens array, so no other code can observe it half built.
When you do need a different value
Different situations call for different tools.
- Derive it. If the new value can be calculated from props, calculate it during render, as
shoutandsorteddid above. Do not store it anywhere. - Copy it. If you need to edit a copy, use spread syntax or the non-mutating array methods, then work on the copy.
- Keep your own state. If the component needs a value that changes over time, give it state with
useState. A common pattern is to use a prop as the starting value. - Ask the owner. If the data belongs to a parent, the child should call a function the parent passed down, and the parent updates its own state. The following chapters cover this pattern.
Here is the third option, a prop used as an initial value.
import { useState } from 'react';
function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
export default function App() {
return <Counter initialCount={5} />;
}The component never writes to initialCount. It reads the prop once, and useState uses it only on the first render. The name initialCount signals this to readers.
Common mistakes
- Assuming
constprotects the data.const items = props.itemsstill points at the parent's array.items.push(x)changes it. - Trusting the lack of an error. Nested mutation throws nothing. If the parent's data changes unexpectedly, search the child components for
sort,reverse,splice,push, and direct assignments. - Mutating inside
.map. Writingitems.map((item) => { item.done = true; return item; })returns the same objects with changed fields. Return{ ...item, done: true }instead. - Fixing it with a deep clone everywhere. You rarely need
structuredCloneon every render. Copy only the levels you change and reuse the rest.
Exercise
A component receives users as a prop and renders them sorted by age with users.sort((a, b) => a.age - b.age). No error appears, but another component that also shows users now lists them in a different order. Why did this happen, and how do you fix it?
Show answer
sort reorders the array in place, and the props object is frozen only at the top level, so the array held by the parent was changed without any error. Every component holding that array sees the new order. Sort a copy instead: [...users].sort((a, b) => a.age - b.age) or users.toSorted((a, b) => a.age - b.age).
Exercise
A child component contains function Tag({ label }) { label = label.trim(); return <span>{label}</span>; }. Does this violate the read-only rule for props? What would you change?
Show answer
It does not mutate the props object. It only reassigns the local destructured variable, so no error occurs and the parent is unaffected. It is still better style to write const trimmed = label.trim(); and render trimmed, because reassigning a parameter makes it look as if the prop was changed.
Exercise
Why does mutating an array prop in place cause problems for a child wrapped in memo?
Show answer
memo compares props by reference. After an in-place change the array keeps the same reference, so the comparison reports no change and React skips re-rendering, which leaves the screen out of date. Creating a new array makes the reference differ, so the comparison detects the change.