React traps · Chapter 2 of 16

Mutating state

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: State and rendering
  • 3 tasks
  • React
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

The lesson

By the end of this case

You can tell mutated state from its symptoms (a change that shows up late, and data changing somewhere else), make it happen on purpose on a test page, fix it with a new array, and pin it down with a test that checks both what the screen shows and what was passed in.

The ticket

PAR-615: Seats appear late, and Undo does not undo. Assigned to you by Rukhsana. Priority: high. Since: the seat map's redesign last week.

Ira, in the design channel at 4:15 pm: "I watched people book on my phone today. They tap a seat and nothing lights up. One man, who already had E8 from yesterday, tapped E7, gave up, tapped the Balcony tab to look at prices, and suddenly E7 was in his seats. Then he pressed Undo my changes to go back to just E8, and nothing happened."

The support tool's session replay for his booking:

16:02:11  tap seat E7         Your seats: E8
16:02:20  tap tab Balcony     Your seats: E8, E7
16:02:31  tap Undo            Your seats: E8, E7

Rukhsana: "The redesign moved the picked seats into state that starts from the booking the server sent. No errors anywhere, the clicks arrive, the handler runs. So ask what React is handed when a seat is tapped, and where that came from. Reproduce it first, then fix it, then make sure it never comes back. You are in SeatPicker.jsx."

Same array, no render

When you call a state setter, React compares the new value with the old one using Object.is. If they are the same, it skips the render: nothing changed, so nothing to draw. For an array, "the same" means the same object, not the same contents:

const a = ['E7'];
const b = a;
b.push('E8');
console.log(Object.is(a, b), a);
console.log(Object.is(['E7'], ['E7']));
true [ 'E7', 'E8' ]
false

So a handler that changes the state's array and hands that array back has asked React for nothing. Here a watchlist pushes a show and sets the same array, and the page has a Dark mode button too:

function watch() {
  shows.push('Pune 52');
  setShows(shows);
}
push, after one click: Watching: nothing
push, after Dark mode: Watching: Pune 52

The push did happen: the array holds Pune 52. React just did not render until the dark mode state changed, and then the next render read the changed array. That is the "it appears after I tap a tab" in the ticket.

Changing what is not yours

There is a second, quieter cost. useState(saved) does not copy saved: the state starts as the very array the parent passed in. Change it in place and you have changed the parent's data too. Any copy you meant to go back to, like the booking as the server has it, is now changed as well, and nothing tells you.

The cure for both is to treat state as read-only: make a new array every time. Spread to add ([...shows, 'Pune 52']), filter to take one out, map to change one:

copy, after one click: Watching: Pune 52

Making it happen on purpose

This one needs no held answers: one tap is enough, as long as nothing else re-renders. Render the picker on a test page with an empty saved array, tap a seat, and read the line before anything else happens.

For the guard, remember the second symptom. A test can keep the array it passes in, in a variable of its own, and look at it afterwards: expect(saved).toEqual([...]) compares an array's contents. Or it can press Undo and read the line.

Your turn

Three tasks, one file each. In repro.jsx, tap a seat that never shows. In SeatPicker.jsx, fix the toggle so every tap shows at once and saved is never changed. In SeatPicker.test.jsx, write the guard: the check runs it beside the original code, the fix and a wrong fix that copies the array after pushing to it. Run both from the workspace folder (cd /workspace, then npx vitest run chapters/02-mutating-state), try it in the Preview, then answer Rukhsana's interview question at the bottom.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    repro.jsx: tap a seat that never shows, on purpose

    Write reproduce() in repro.jsx. Render SeatPicker with saved set to an empty array and seats set to a row such as E5, E6, E7, E8 and E9. Tap the E7 button once and nothing else (a class tab would re-render the page and show the seat), and resolve to the text of the Your seats line.

    The check runs your reproduce() twice: beside the original SeatPicker.jsx it must resolve to 'Your seats: none' (the tap changed nothing on screen), and beside a fixed SeatPicker.jsx it must resolve to 'Your seats: E7'. So it must really tap E7 and read the line. reproduce() must finish within 5 seconds.

  2. Task 2

    SeatPicker.jsx: a tapped seat shows at once, and Undo works

    Fix SeatPicker({ saved, seats }) in SeatPicker.jsx. Tapping a seat adds it to the Your seats line at once, after the seats already there, in the order tapped, and presses its button (aria-pressed true). Tapping it again takes it off at once (aria-pressed false), and that works for saved seats too. Undo my changes goes back to the saved seats, as often as it is pressed.

    SeatPicker must never change the saved array passed in: it is the booking as the server has it. Keep the line's words (Your seats: B4, B6 and Your seats: none), the seat buttons, the class tabs and the Undo button as they are. The check uses its own seats, keeps a copy of saved to compare, and presses Undo; a fix that copies the array after changing it renders, but has already changed saved.

  3. Task 3

    SeatPicker.test.jsx: a test that would have caught it

    Write a vitest test file, SeatPicker.test.jsx, that would have caught this bug before it shipped. The check runs your file three times: beside the original SeatPicker.jsx, where at least one test must fail; beside the fixed SeatPicker.jsx, where every test must pass; and beside a wrong fix that copies the array after push, so it renders but still changes saved, where at least one test must fail.

    So test both sides of the ticket: tap one seat and expect it in the Your seats line at once, and check that Undo my changes goes back to saved, or that the saved array you passed in is unchanged. No real waiting: each test must finish within 5 seconds.

What you will learn

  • repro.jsx: tap a seat that never shows, on purpose
  • SeatPicker.jsx: a tapped seat shows at once, and Undo works
  • SeatPicker.test.jsx: a test that would have caught it

More in State and rendering

Build "Mutating state" yourself

Parda's web app runs on React, and Rukhsana, its senior frontend engineer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.