ReactEasy

How to update state?

Call the setter returned by useState (or dispatch from useReducer) with a new value or an updater function. Never mutate state directly: create new objects and arrays so React can detect the change and re-render.

Two forms

  • Direct value: setName("Ada").
  • Updater function: setCount((prev) => prev + 1). Use it whenever the next value depends on the previous one, especially for multiple updates in a row or inside async callbacks, to avoid stale values.

Objects

  • setUser({ ...user, email }) copies and overrides.
  • Nested: setUser((u) => ({ ...u, address: { ...u.address, city } })).
  • For deep updates, Immer (useImmer, or produce) lets you write "mutating" code that produces a new object.

Arrays

  • Add: [...list, item] or [item, ...list].
  • Remove: list.filter((x) => x.id !== id).
  • Update: list.map((x) => (x.id === id ? { ...x, done: true } : x)).
  • Sort or reverse: copy first, or use ES2023 toSorted() and toReversed().
  • Avoid push, splice, sort and direct assignment on state arrays.

Things to know

  • State updates are batched and applied on the next render; reading the variable right after setX still gives the old value.
  • Setting the same value (by Object.is) bails out of re-rendering.
  • Do not call setters during render (infinite loop), except for the rare "adjust state when a prop changes" pattern with a guard.

Code example

tsx
1import { useState } from "react";
2
3type Item = { id: number; name: string; qty: number };
4
5export function Cart() {
6 const [items, setItems] = useState<Item[]>([{ id: 1, name: "Pen", qty: 1 }]);
7 const [count, setCount] = useState(0);
8
9 const add = () => setItems((prev) => [...prev, { id: Date.now(), name: "Notebook", qty: 1 }]);
10 const remove = (id: number) => setItems((prev) => prev.filter((i) => i.id !== id));
11 const increment = (id: number) =>
12 setItems((prev) => prev.map((i) => (i.id === id ? { ...i, qty: i.qty + 1 } : i)));
13
14 const addThree = () => {
15 // Updater form: each call sees the latest value, so count goes up by 3
16 setCount((c) => c + 1);
17 setCount((c) => c + 1);
18 setCount((c) => c + 1);
19 };
20
21 return (
22 <div>
23 {items.map((i) => (
24 <p key={i.id}>
25 {i.name} x{i.qty} <button onClick={() => increment(i.id)}>+</button>
26 <button onClick={() => remove(i.id)}>Remove</button>
27 </p>
28 ))}
29 <button onClick={add}>Add item</button>
30 <button onClick={addThree}>Clicked {count}</button>
31 </div>
32 );
33}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app