React traps · Chapter 1 of 16
setState with a stale value
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.
Why you need this
Nothing here is an error. Each call is a fine request, and the last one wins. Click slowly and every click sees a fresh render, so it looks right. It goes wrong only when two updates are worked out from the same old number, and an await makes that easy: the handler waits, the user taps again, and the second tap's handler was made by the same render as the first.
The cure is to stop computing from the snapshot. Pass setTickets a function, an updater, and React calls it with the count as it is when the update is applied, one update after the other:
setTickets((n) => n + 1);
setTickets((n) => n + 1);
updater, after one click: Tickets: 2The lesson
By the end of this case
You can tell a stale value in setState from its symptoms, make it happen on purpose on a test page with answers you hold back, fix it with an updater function, and pin it down with a test that fails on the bug and passes on the fix.
The ticket
PAR-612: The seat count is short. Assigned to you by Rukhsana. Priority: high. Since: Monday's show page release.
Datta, in the support channel at 10:40 pm: "A family at the counter tonight, four of them, for Ghar Wapsi Express at 9:30. On the phone they tapped Add a seat four times, quick quick, and the page said 1 seat, so they paid ₹200 and came to the counter angry. The box office had held four seats for them. Three sat held and unpaid for ten minutes, and we turned away a couple at the window because the show looked full."
The box office's hold log for that booking, with the basket's line:
22:14:03.120 boxoffice hold T0023 seat for PB82214: held 10 min
22:14:03.388 boxoffice hold T0023 seat for PB82214: held 10 min
22:14:03.611 boxoffice hold T0023 seat for PB82214: held 10 min
22:14:03.840 boxoffice hold T0023 seat for PB82214: held 10 min
22:14:04.016 basket PB82214: 1 seat, ₹200 to pay
22:24:03.120 boxoffice hold T0023: 3 seats released, not paid
Rukhsana: "Monday's show page asks the box office to hold a seat before it counts it. The old page counted at once and held later. Tap slowly and it is fine; tap fast and seats go missing. Think about which render's number each tap is adding 1 to. Reproduce it first, then fix it, then make sure it never comes back. You are in SeatCounter.jsx."
A render is a snapshot
Every render calls your component again, and the state it reads is that render's copy: a number frozen for that render. An event handler made during a render sees that copy, even after setState. Here a button sets the count twice:
function addTwo() {
setTickets(tickets + 1);
setTickets(tickets + 1);
console.log('tickets in the handler:', tickets);
}
Clicked once on a test page:
tickets in the handler: 0
after one click: Tickets: 1
Both calls said "make it 0 + 1". setTickets does not change tickets; it asks React for a new render, and that render gets the new number.
Making it happen on purpose
You cannot tap fast enough to reproduce a race every time, so the test does the tapping and you decide when the server answers. The lab has vitest and Testing Library: render puts a component on a test page, screen finds things the way a person does (by role, label or text), fireEvent.click taps, and act lets React finish its updates.
The trick is a fake server that does not answer until you say so. Here is a Remind me button whose server call is held back:
let answer;
const remind = () => new Promise((resolve) => { answer = resolve; });
render(<RemindMe showId="S14" remind={remind} />);
fireEvent.click(screen.getByRole('button'));
console.log('while waiting:', screen.getByRole('button').textContent);
await act(async () => answer(true));
console.log('after the answer:', screen.getByRole('button').textContent);
while waiting: Saving...
after the answer: Reminder set
Keep every call's resolve in an array and you can tap as often as you like before any answer comes, then answer them in any order.
A test that would have caught it
A guard test turns the repro into something that runs before every release. A vitest file says it('name', ...) for each test and expect(...) for each check. This one passes; with the button's ok check removed, it fails (trimmed):
it('says Try again when the server says no', async () => {
let answer;
const remind = () => new Promise((resolve) => { answer = resolve; });
render(<RemindMe showId="S14" remind={remind} />);
fireEvent.click(screen.getByRole('button', { name: 'Remind me' }));
await act(async () => answer(false));
expect(screen.getByRole('button')).toHaveTextContent('Try again');
});
FAIL chapters/remind-demo/RemindMe.test.jsx > says Try again when the server says no
Expected element to have text content:
Try again
Received:
Reminder set
A good guard fails on the bug and passes on the fix, and it tests what the customer does: quick taps, not slow ones.
Your turn
Three tasks, one file each. In repro.jsx, lose a seat on purpose: tap twice before the box office answers. In SeatCounter.jsx, fix it. In SeatCounter.test.jsx, write the guard: the check runs it beside the original code, the fix and a wrong fix that disables the button while a hold waits. Run both from the workspace folder (cd /workspace, then npx vitest run chapters/01-stale-state), and watch it happen 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.
- Task 1
repro.jsx: lose a seat on purpose
Write reproduce() in repro.jsx. Build a fake holdSeat(showtimeId) that does not answer straight away: it returns a promise and keeps its resolve function in an array, so you can answer later. Render SeatCounter with any showtimeId and your fake, tap the Add a seat button twice, then answer both holds with true inside act, and resolve to the text of the seat count paragraph.
The check runs your reproduce() twice: beside the original SeatCounter.jsx it must resolve to '1 seat' (two seats held, one counted), and beside a fixed SeatCounter.jsx it must resolve to '2 seats'. So both taps must come before any answer. No real waiting: you give the answers, and reproduce() must finish within 5 seconds.
- Task 2
SeatCounter.jsx: every seat the box office holds is counted
Fix SeatCounter({ showtimeId, holdSeat }) in SeatCounter.jsx. Every tap of Add a seat asks holdSeat(showtimeId), even while another hold is still waiting. When a hold answers true, one more seat is counted, however many taps came before the answers and in whatever order the answers arrive. When it answers false, no seat is counted and the note That seat was just taken shows. A seat is counted only once its answer has come.
Keep the paragraph's words as they are (0 seats, 1 seat, 2 seats), the button's name and the note. The check uses its own showtimes, taps several times before answering and answers out of order, and a fix that disables the button while a hold waits loses the second tap: as wrong as the bug.
- Task 3
SeatCounter.test.jsx: a test that would have caught it
Write a vitest test file, SeatCounter.test.jsx, that would have caught this bug before the release. The check runs your file three times: beside the original SeatCounter.jsx, where at least one test must fail; beside the fixed SeatCounter.jsx, where every test must pass; and beside a wrong fix that disables the button while a hold is waiting, where at least one test must fail.
So test it the way the family used it: render SeatCounter with a fake holdSeat whose answers you hold back, tap Add a seat twice before any answer, answer both with true, and expect 2 seats. A test of a false answer is welcome too. No real waiting: each test must finish within 5 seconds.
What you will learn
- repro.jsx: lose a seat on purpose
- SeatCounter.jsx: every seat the box office holds is counted
- SeatCounter.test.jsx: a test that would have caught it
More in State and rendering
Build "setState with a stale value" 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.