Sub topic 5
Why props are read-only
This chapter assumes you can pass and read props, destructure them, and use useState. It explains the rule that a component must never change its own props, and it shows the mistakes that break that rule.
The rule
A component receives props from its parent. The parent owns that data, so the child may read it but must not change it. React treats a component as a pure function of its inputs. Given the same props, it should return the same JSX and have no side effects on its inputs.
What happens when you assign to a prop
React freezes the props object in development. Modules run in strict mode, so assigning to a prop throws an error.
function Greeting(props) {
props.name = props.name.toUpperCase(); // TypeError
return <h1>Hello, {props.name}!</h1>;
}The error reads Cannot assign to read only property 'name' of object. To transform a prop, compute a new value in a local variable:
function Greeting({ name }) {
const shout = name.toUpperCase();
return <h1>Hello, {shout}!</h1>;
}The freeze is shallow
Object.freeze protects only the top level of the object. If a prop is an object or an array, its contents are not frozen. Mutating them raises no error, and that is why this mistake is common.
function SortedList({ items }) {
items.sort(); // mutates the parent's array
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}sort reorders the array in place, so the parent's data changes without the parent knowing. React will not re-render the parent. Other components that read the same array now show a different order. Copy the array first:
function SortedList({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}Methods that mutate in place include push, pop, splice, sort, and reverse. Prefer map, filter, spread, or toSorted, which return new values.
Common errors
| Mistake | Why it is wrong | Fix |
|---|---|---|
| `props.count = 5` | Throws in strict mode | Compute a local variable |
| `user.name = "x"` on a prop object | Changes the parent's data silently | Copy with `{ ...user, name: "x" }` |
| `items.push(x)` on a prop array | Parent never re-renders | Ask the parent to update through a callback |
| Calling `setState` on the parent's data from the child directly | The child has no access to it | Receive a callback prop |
How to change data the right way
If a child needs the data to change, the owner must change it. There are two cases.
- The child needs a modified view of the data. Derive it during render, as
shoutandsorteddo above. - The child needs the parent's data to change. Call a callback prop, and the parent updates its own state.
import { useState } from 'react';
function Counter({ count, onIncrement }) {
return <button onClick={onIncrement}>Clicked {count} times</button>;
}
export default function App() {
const [count, setCount] = useState(0);
return <Counter count={count} onIncrement={() => setCount(count + 1)} />;
}Counter never writes to count. It asks App to change it, and App re-renders with a new prop value.
Why React insists
- Predictable rendering. If rendering changes inputs, the output depends on the order components render in.
- Change detection. React learns about changes through new state values, not by watching for mutations.
- Strict Mode. In development, React renders components twice to expose impure code. A component that mutates a prop will behave differently on the second pass.
Exercise
A child receives todos as a prop and runs todos.push({ text: "New" }) inside an event handler. No error appears, but the parent's list never updates on screen. Why, and what should the child do instead?
Show answer
The freeze is shallow, so pushing onto the array is allowed and changes the parent's data in place. React only re-renders when state is set, and no state was set, so the screen does not update. The child should call a callback prop such as onAdd(newTodo). The parent then calls setTodos([...todos, newTodo]).