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.

In shortReplace, do not mutate: use spread to copy objects and arrays. Use setX(prev => ...) when you need the latest value.

Theory in plain words

Mutate vs replaceMutate (wrong)user.name = "Ravi"same object referenceReact may skip the updateReplace (right)setUser({ ...user, name })new object referenceReact renders the change
Mutate vs replace

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

Click once: why +1 and not +3?Try it Yourself

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

Update one fieldTry it Yourself

Arrays: add, remove, change

GoalAvoid (mutates)Use (returns a new array)
Addpush, unshift[...list, item]
Removesplicelist.filter(x => x.id !== id)
Change onelist[i] = vlist.map(x => x.id === id ? { ...x, done: true } : x)
Sort / reversesort, reversetoSorted, toReversed (or copy first)
A tiny todo listTry it Yourself

Nested objects

Copy every level you changeTry it Yourself

Deep nesting is painful. Keep state flat when you can, or use a helper such as Immer.

Tip:If the next state does not depend on the previous one, a plain 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?

2. When do you need setN(n => n + 1)?

3. Why is mutating state a problem?

4. How do you remove an item by id?

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.