Skip to article content
FrontendXLesson 03 / 40

State, Updates and Immutability

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

beginner · about 50 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Test

What you will be able to do

#
  • Model component state with useState.
  • Use updater functions to avoid stale state.
  • Apply immutable updates to objects and arrays.

Overview

#

State is a snapshot

useState returns the current value for this render and a setter. The value is a snapshot: within a single render, state never changes, even after you call the setter. React schedules a re-render and the next render sees the new value.

snippet.tsx
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Updater functions

When the next value depends on the previous one, pass an updater function. This reads the latest queued value instead of the snapshot captured by the closure.

snippet.tsx
setCount((c) => c + 1);
setCount((c) => c + 1); // adds 2, not 1

With setCount(count + 1) called twice in one handler, both calls use the same snapshot and the result increases by one. Updater functions queue correctly.

Automatic batching

React 19 batches all state updates, including those inside promises, timeouts and native event handlers. Multiple setters in one task produce a single re-render. If you need to read a value after an update, do not read the state variable in the same handler; compute the next value or use an effect only when truly synchronizing with an external system.

Immutable updates

React compares state by reference. Mutating an object or array in place keeps the same reference, so React may skip the update. Always create new objects and arrays.

snippet.tsx
setUser((u) => ({ ...u, name: "Grace" }));
setItems((list) => [...list, newItem]);
setItems((list) => list.filter((i) => i.id !== id));
setItems((list) => list.map((i) => (i.id === id ? { ...i, done: true } : i)));

For nested updates, spread each level you change. If updates get complex, move them into a reducer (see the context and architecture lesson).

Choosing state

Keep only what cannot be derived. If a value can be computed from props or other state, compute it during render instead of storing it. Duplicated state is the most common source of inconsistent UI.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What value is displayed after the button is clicked once?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    function Counter() {
      const [n, setN] = useState(0);
      return (
        <button
          onClick={() => {
            setN(n + 1);
            setN(n + 1);
          }}
        >
          {n}
        </button>
      );
    }
    Choose the best answer
  2. Exercise 2Implement

    Implement a TodoList that adds items and toggles their done flag using immutable updates.

    starter.tsx
    type Todo = { id: string; text: string; done: boolean };
    
    export function TodoList() {
      const [todos, setTodos] = useState<Todo[]>([]);
      // add and toggle
      return null;
    }

    Reveal the reference answer
    reference.tsx
    type Todo = { id: string; text: string; done: boolean };
    
    export function TodoList() {
      const [todos, setTodos] = useState<Todo[]>([]);
      const [text, setText] = useState("");
    
      function add() {
        if (!text.trim()) return;
        setTodos((list) => [...list, { id: crypto.randomUUID(), text, done: false }]);
        setText("");
      }
    
      function toggle(id: string) {
        setTodos((list) =>
          list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
        );
      }
    
      return (
        <div>
          <input value={text} onChange={(e) => setText(e.target.value)} />
          <button onClick={add}>Add</button>
          <ul>
            {todos.map((t) => (
              <li key={t.id}>
                <label>
                  <input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />
                  {t.text}
                </label>
              </li>
            ))}
          </ul>
        </div>
      );
    }

    Authored expected output: Adding text appends a todo; clicking a checkbox toggles its done state; keys keep rows stable.

    Adding uses a new array spread. Toggling maps to a new object for the matched id, preserving immutability. The stable id key keeps row identity during reorder or deletion.

  3. Exercise 3Debug

    This component does not update when an item is pushed. Explain and fix.

    starter.tsx
    function List() {
      const [items, setItems] = useState<string[]>([]);
      function add() {
        items.push("new");
        setItems(items);
      }
      return <button onClick={add}>{items.length}</button>;
    }

    Reveal the reference answer
    reference.tsx
    function List() {
      const [items, setItems] = useState<string[]>([]);
      function add() {
        setItems((list) => [...list, "new"]);
      }
      return <button onClick={add}>{items.length}</button>;
    }

    Authored expected output: Each click increments the displayed count by one.

    push mutates the array in place and setItems receives the same reference, so React bails out of the update. Creating a new array with spread gives React a new reference to compare.

  4. Exercise 4Test

    Describe a test that proves the counter increments by exactly one per click when using an updater function.

    starter.tsx
    setN((x) => x + 1)

    Reveal the reference answer
    reference.tsx
    Render the counter, read the button text (0), click once, assert the text is 1, click again, assert 2. Use userEvent.click to exercise the real event path.

    Authored expected output: Assertions: 0, then 1, then 2 after successive clicks.

    Testing through the event path rather than calling the setter directly proves the wiring from click to state to rendered output, which is the behavior learners depend on.

Common misconceptions

#
  • State updates immediately. State is a snapshot; the new value appears on the next render.
  • setCount(count + 1) twice adds two. Both calls read the same snapshot, so it adds one; use an updater.
  • Mutating state is fine if the value looks right. React compares by reference and may skip the update.
  • Derived values should be stored in state. Store the source and compute derived values during render.

Follow-up practice

#
  • react-events-and-forms
  • react-context-and-state-architecture

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.