Sub topic 1
State Is a Snapshot, Not a Variable You Edit
Prerequisites
This chapter assumes JavaScript objects, the spread operator, React function components, useState, and event handling.
State Is a Snapshot
React state is a snapshot: a fixed value captured for one render. Calling a state setter requests another render with a new value. It does not turn the current value into a variable that you can edit in place.
For example, name keeps its current value throughout the render that created it:
function Greeting() {
const [name, setName] = useState('Ada');
function rename() {
setName('Grace');
console.log(name); // Still "Ada" in this render
}
return <button onClick={rename}>{name}</button>;
}The next render can display "Grace". The current render still sees its original snapshot.
Why Mutating State Does Not Work
Mutation means changing an existing object or array. This code changes the object directly:
person.firstName = 'Grace';
setPerson(person);The setter receives the same object reference. React may treat that value as unchanged, so the screen might not update. Even when another update causes a render, direct mutation makes the data harder to reason about because older snapshots can appear to change.
Treat State as Read-Only: Replace, Don't Change
Read state without modifying it. When something changes, create a replacement value and pass that value to the setter.
Updating Objects with the Spread Operator
The object spread operator copies an object's properties. Put changed properties after the spread so they replace the old values:
const [person, setPerson] = useState({
firstName: 'Ada',
lastName: 'Lovelace',
});
function handleFirstNameChange(event) {
setPerson({
...person,
firstName: event.target.value,
});
}The original person remains unchanged. The new object has the old lastName and the new firstName.
Spread Makes a Shallow Copy
A shallow copy duplicates only the outer object. Nested objects still have their original references. Therefore, spreading the outer object alone does not safely update a nested property. Copy every object on the path to the changed value.
Exercise
Why is setPerson({ ...person, firstName: 'Grace' }) safer than person.firstName = 'Grace'; setPerson(person)?
Show answer
It creates a new outer object, so React receives a new reference while the original snapshot stays unchanged.