Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 3

State, Events and Immutable Updates

Worked example: make a packing list interactive — controlled inputs, event handlers, state that is always replaced rather than edited, and values derived during render.

Contentsand lesson path

What you will learn

  • Handle user events and manage local state with useState, updating objects and arrays immutably and lifting shared state to the closest common parent.

Prerequisites: JavaScript Foundations

01. The problem

The profile card from the last two lessons never changes: render it a thousand times, get the same output. Real interfaces respond — you type, tick, submit — and the screen follows. React's answer is state: data a component owns and can change between renders by calling a setter. When the setter is called, React schedules a new render of that component, and the new output replaces the old.

This worked example builds the packing list from your sketch: an input that adds items, checkboxes that tick them, and a running "packed" count that must never drift out of step with the list. Along the way it shows the two habits that separate comfortable React code from fragile code: updating state immutably (always passing a new value, never editing the old one) and keeping derived values out of state. If you have done the DOM lessons, note how much disappears: no querySelector, no manual re-render — the handlers change state, and rendering follows in React's own way.

02. Step 1: state and event handlers

TSX · src/shopping-list.tsx
import { useState } from 'react';

type Item = { id: string; name: string; done: boolean };

function AddForm({ onAdd }: { onAdd: (name: string) => void }) {
  const [draft, setDraft] = useState('');
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const name = draft.trim();
        if (!name) return;
        onAdd(name);
        setDraft('');
      }}
    >
      <label htmlFor="item-name">Item name</label>
      <input
        id="item-name"
        value={draft}
        onChange={(event) => setDraft(event.target.value)}
      />
      <button type="submit">Add</button>
    </form>
  );
}

State is created with useState(initial) and read from the first element of the pair it returns; the second element is the setter. Handlers are ordinary props — onChange, onSubmit — and React wires them for you. This input is controlled: its value comes from state and every keystroke writes back through onChange, so the state is the single source of truth for what the box shows. Clearing draft after adding is then one setter call, not DOM surgery. The form handles submit rather than the button's click, which keeps Enter-to-submit working — the same keyboard-first thinking as in listeners and default actions, only expressed as props.

03. Step 2: replace, never edit

TSX · src/shopping-list.tsx (continued)
function Summary({ done, total }: { done: number; total: number }) {
  return (
    <p role="status">
      {done} of {total} packed
    </p>
  );
}

export function ShoppingList() {
  const [items, setItems] = useState<Item[]>([
    { id: 'boots', name: 'Walking boots', done: false },
    { id: 'jacket', name: 'Rain jacket', done: true },
  ]);

  function addItem(name: string) {
    setItems([...items, { id: crypto.randomUUID(), name, done: false }]);
  }

  function toggle(id: string) {
    setItems(items.map((it) => (it.id === id ? { ...it, done: !it.done } : it)));
  }

  const doneCount = items.filter((it) => it.done).length;

Look closely at the two updates, because both replace the state instead of editing it. addItem spreads the old array into a new one and appends; toggle maps to a new array whose one changed element is a new object built by spreading the old. The originals are untouched.

Why so ceremonious? React decides whether anything changed by comparing the value you pass with the one it holds, using Object.is — a check of identity, not of contents. items.push(x); setItems(items) hands back the same array, the comparison sees no change, and the interface silently stays stale: no error, nothing in the console. Tooling only partly helps: the React Compiler lint rule react-hooks/immutability (in eslint-plugin-react-hooks 7) reports a mutation it can see during render, but it does not report this one inside an event handler, so the habit has to be yours. Treat every state value as read-only and build the new one — the tools from arrays and objects — spread, map, filter — are the whole toolkit.

The last line of the block deserves equal attention. doneCount is computed during render from items — not stored. Storing it in a second useState would create two copies of one truth, and every update would have to remember to keep them in step; forgetting once means a count that lies. Anything you can calculate from state you already have, calculate during render.

04. Step 3: the tree that ties it together

TSX · src/shopping-list.tsx (continued)
  return (
    <section>
      <h2>Packing list</h2>
      <AddForm onAdd={addItem} />
      <Summary done={doneCount} total={items.length} />
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <label>
              <input
                type="checkbox"
                checked={item.done}
                onChange={() => toggle(item.id)}
              />{" "}
              {item.name}
            </label>
          </li>
        ))}
      </ul>
    </section>
  );
}

The state lives in ShoppingList, one level above the two pieces that need it: AddForm receives the addItem callback, Summary receives numbers computed from the same array. Neither child owns or copies the data, so both are always in step — one source of truth, flowing down. This arrangement is called lifting state up, and the rule of thumb is to place state in the nearest common parent of everything that reads it. The list itself is rendered with map, giving each row a key — the key earns its own lesson next, but the habit starts now: keys come from the data (item.id) rather than from the row's position.

05. Step 4: snapshots and queued updates

This step checks the behaviour with a test: Testing Library renders the component in jsdom (a simulated browser DOM), clicks a button the way a user would, and asserts on the screen. To run it, add the test tools to the project — npm install -D [email protected] [email protected] @testing-library/[email protected] @testing-library/[email protected] @testing-library/[email protected] @testing-library/[email protected], the versions this lesson was checked with, beside React 19.3.1 — and the two small files below. The setup file adds matchers such as toBeVisible and unmounts each test's component afterwards; without that cleanup, a second test in the same file would also see the first test's buttons. The frontend testing skill explains both files in depth.

TypeScript · vitest.config.ts and src/setup-tests.ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: { environment: 'jsdom', setupFiles: './src/setup-tests.ts' },
});

// src/setup-tests.ts
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';

afterEach(cleanup);
TSX · src/state.test.tsx
import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { it, expect } from 'vitest';

function Stepper() {
  const [count, setCount] = useState(0);
  function addEleven() {
    setCount((c) => c + 1);
    setCount((c) => c + 10);
  }
  return (
    <section>
      <p aria-live="polite">Quantity: {count}</p>
      <button type="button" onClick={addEleven}>
        Add eleven
      </button>
    </section>
  );
}

it('queues updates from the latest value', async () => {
  const user = userEvent.setup();
  render(<Stepper />);
  await user.click(screen.getByRole('button', { name: 'Add eleven' }));
  expect(screen.getByText('Quantity: 11')).toBeVisible();
});
Expected output · npx vitest run src/state.test.tsx (the RUN, Start at and Duration lines and the timing on the ✓ line vary and are left out)
 ✓ src/state.test.tsx (1 test)

 Test Files  1 passed (1)
      Tests  1 passed (1)

The test passes, and the reason it passes is worth understanding. State in a given render is a snapshot: count is a fixed number for the lifetime of that render, however many times you call setCount. Notice how addEleven queues two updates in one event handler: if it called setCount(count + 1); setCount(count + 10);, both would read snapshot 0 and overwrite each other, ending at 10. By passing updater functions, each receives the latest pending value in the queue (0 -> 1 -> 11), arriving at 11. Reading count right after calling its setter shows the old snapshot too — the new value arrives with the next render.

06. Check your understanding

Practice check · 3 questions

State in practice

Three decisions from the packing list and beyond.

Q1. State holds `const [form, setForm] = useState({ name: "Ada", drafts: 2 })`. A handler must raise `drafts` by one. Which update is correct?
Q2. Inside one event handler, `setCount(count + 1)` runs, and the very next line logs `count`. What does the log show?
Q3. The list holds items in state and the header must show how many are done. Where does that number live?
Practice only: not graded, not saved, not evidence.

07. Apply it

Extend the packing list twice. First add a remove action: an extra button per row whose handler filters the item out — think about which array tool replaces the element and whether the object spread is needed there. Then give each item a packAfter note that only its own row edits locally, and decide which state belongs to the row and which to the parent. Write a Testing Library test for each change before you implement it: click, then assert on the status line. When it works, compare your handlers against the warning list above — every one of those five mistakes is a real code review finding.

08. Review prompt

Without looking back: write down the three array operations this lesson used for add, toggle and derive, and why each leaves the original array alone. Then explain a controlled input in two sentences, and say why setCount((c) => c + 1) is the safer form than setCount(count + 1) even though both often look identical in effect.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check