State & Events
React Updating Objects in State
State must be treated as immutable. To change one field of an object in state, create a new object with the spread operator and pass that to the setter — never assign to a property of the existing object.
What is Updating Objects in State in React?
State must be treated as immutable. To change one field of an object in state, create a new object with the spread operator and pass that to the setter — never assign to a property of the existing object.
Why Updating Objects in State matters
React decides whether to re-render by comparing references with Object.is. Mutating an object leaves the reference unchanged, so React sees no difference and skips the update entirely.
Updating Objects in State example
const [form, setForm] = useState({ name: '', email: '', city: 'Pune' });
// WRONG — same reference, React sees no change
form.name = 'Riya';
setForm(form);
// RIGHT — new object, old fields copied
setForm({ ...form, name: 'Riya' });
// RIGHT — functional form, safest under batching
setForm(prev => ({ ...prev, name: 'Riya' }));How this works
The spread copies every existing key, then name overrides one of them. The result is a brand-new object, so the reference changes and React re-renders.
Nested objects need spreads at every level
setUser(prev => ({
...prev,
address: { ...prev.address, city: 'Bengaluru' },
}));A shallow spread copies the outer object only, so the nested address would still be shared. Spread each level you are changing.
Key points to remember
- Never mutate — always produce a new object.
- Wrap the object literal in parentheses inside an arrow function, otherwise the braces are read as a function body.
- For deeply nested state, consider useReducer or a library like Immer.
Common mistakes with Updating Objects in State
- Writing the updater as prev => { ...prev } without wrapping the object in parentheses — the braces are read as a function body and it returns undefined.
- Mutating a nested object and wondering why nothing updates.
- Keeping deeply nested state when flattening it would be far simpler.
React Updating Objects in State— Interview Questions & FAQs
Why does my component not re-render after changing a state object?+
You mutated it in place, so the reference is identical and React skips the render. Always create a new object with the spread operator.
