Home / Learn React / Updating State Correctly
Updating State Correctly
State updates have a few rules: treat state as read only, use the functional form when the new value depends on the old one, and copy objects and arrays instead of changing them.
Theory in plain words
What it is
Updating state means giving React a new value. For numbers and strings that is easy. For objects and arrays it means making a new copy with your change, never editing the old one.
Why we use it
React decides whether to re-render by comparing the old and new value. If you edit an object in place its reference stays the same, so React may skip the update. Copies also keep older renders safe and make bugs easier to find.
How it works
State updates are batched: several set calls in one event cause one render. The value you see inside the handler is the snapshot from that render. The functional form setN(n => n + 1) receives the latest queued value.
Where it is used
- Counters that update several times in one click
- Forms with many fields in one object
- Todo lists: add, remove, toggle
- Shopping carts and settings
State is a snapshot
In the first button n is 0 in the whole handler, so every call sets 1. The updater form uses the latest value.
Objects: copy with spread
Arrays: add, remove, change
| Goal | Avoid (mutates) | Use (returns a new array) |
|---|---|---|
| Add | push, unshift | [...list, item] |
| Remove | splice | list.filter(x => x.id !== id) |
| Change one | list[i] = v | list.map(x => x.id === id ? { ...x, done: true } : x) |
| Sort / reverse | sort, reverse | toSorted, toReversed (or copy first) |
Nested objects
Deep nesting is painful. Keep state flat when you can, or use a helper such as Immer.
setX(value) is fine. Use the updater form when it does.Quick quiz
1. What is the correct way to add an item to an array in state?
Create a new array with spread.
2. When do you need setN(n => n + 1)?
The updater always receives the latest queued state.
3. Why is mutating state a problem?
React compares references; mutating hides the change.
4. How do you remove an item by id?
filter returns a new array without the item.
Common questions
What is the correct way to add an item to an array in state?
setList([...list, x]). Create a new array with spread.
When do you need setN(n => n + 1)?
When the new value depends on the previous value, especially several updates in one event. The updater always receives the latest queued state.
Why is mutating state a problem?
The reference is the same so React may not re-render, and old snapshots break. React compares references; mutating hides the change.