React traps · Chapter 5 of 16
State copied from props
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
- In the all labs plan
The first 2 chapters of React traps are free. This one comes with the all labs plan.
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: a stale total on purpose
Write reproduce() in repro.jsx. Render BasketSummary with one Middle seat, like { id: 'E7', price: 180 }, then rerender it with two Middle seats at ₹180, as the page does when a second seat is tapped, and resolve to the text of the Total paragraph.
The check runs your reproduce() twice: beside the original BasketSummary.jsx it must resolve to 'Total ₹200' (the first seat's total, still), and beside a fixed BasketSummary.jsx it must resolve to 'Total ₹400' (two seats at ₹180 and a ₹20 fee each). So it must really rerender with the new seats. reproduce() must finish within 5 seconds.
- Task 2
BasketSummary.jsx: the total always matches the seats
Fix BasketSummary({ seats }) in BasketSummary.jsx. On every render the total must match the seats it is given now: every seat's price plus a ₹20 booking fee a seat, and Total ₹0 for no seats, whether seats are added, removed or swapped for a seat of another price.
Keep the two paragraphs' words (0 seats, 1 seat, 2 seats and Total ₹400) as they are. The check uses its own seats and prices and rerenders six times; one step swaps a seat for one of another price, so the number of seats does not change but the total must.
- Task 3
BasketSummary.test.jsx: a test that would have caught it
Write a vitest test file, BasketSummary.test.jsx, that would have caught this bug before it shipped. The check runs your file three times: beside the original BasketSummary.jsx, where at least one test must fail; beside the fixed BasketSummary.jsx, where every test must pass; and beside a wrong fix that copies the total into state again only when the number of seats changes, where at least one test must fail.
So rerender with other seats and expect the new total: add a seat, and also swap a seat for one of another price, so the count stays the same and the total must not. No real waiting: each test must finish within 5 seconds.
What you will learn
- repro.jsx: a stale total on purpose
- BasketSummary.jsx: the total always matches the seats
- BasketSummary.test.jsx: a test that would have caught it
More in State and rendering
Build "State copied from props" 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.
The first 2 chapters of React traps are free. This one comes with the all labs plan.