React · Chapter 12 of 26
Reducers, every change in one place
By the end of this chapter you can move a component's state changes into a reducer, a pure function that takes the state and an action and returns the next state; keep that state with useReducer and change it with dispatch; test a reducer on its own, without React; make it throw on an action it does not know; and choose between useState and useReducer. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: State
- 4 tasks
- React
- In the all labs plan
The first 2 chapters of React are free. This one comes with the all labs plan.
Why you need this
Parda's checkout page has grown. Ira's design has the four booking steps at the top, a snack counter with a basket under it (add a snack, one more, one less, remove it, clear the basket), and a box for group tickets, which schools book for Diwali week: a seat class, a number of tickets and a Pay button. Every one of those buttons changes the same few pieces of state.
With what you know so far, each button gets a handler, and each handler calls the setters it needs. That works while there are two buttons. With five buttons and three pieces of state, the rules are spread across five functions: the handler for "Balcony" must remember that the total depends on the class, the handler for "Start again" must remember to reset the total as well as the tickets. Datta tried the group box this week: three tickets, then Balcony, and the Pay button still said ₹540, the Middle price. It is the October bug again, in a new place: one handler forgot one setter.
Rukhsana wants every rule in one place, where it can be read at once and tested without clicking through a page.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
cart.js: the basket's reducer
Parda's snack basket is an array of lines, one per snack, like [{ id: 'samosa', name: 'Samosa', price: 40, qty: 2 }]. Write cartReducer(cart, action) in cart.js, exported by name as the starter has it: it gets the basket and one action and returns the next basket, for four actions:
{ type: 'add', item: { id, name, price } }: the line with that id gets qty + 1; a snack not in the basket yet goes at the end with qty 1 (and its id, name and price).
{ type: 'remove', id }: the line with that id leaves the basket.
{ type: 'setQty', id, qty }: that line's qty becomes qty, and qty 0 removes the line.
{ type: 'clear' }: an empty basket, [].
Any other type throws an Error whose message is Unknown action: and the type, so { type: 'ad' } throws Unknown action: ad.
A reducer is pure: never change the basket you are given or its lines. Return a new array, with new objects for the lines that change. The Check calls cartReducer on its own with baskets it has frozen, so a push or a qty += 1 throws.
- Task 2
BookingSteps.jsx: the booking's four steps
Booking on Parda takes four steps, in this order: seats, details, pay, done. In BookingSteps.jsx write two things.
bookingFlow(step, action), exported by name: it gets the step, one of those four words, and returns the next step. { type: 'next' } gives the step after this one, and done stays done. { type: 'back' } gives the step before, seats stays seats, and done stays done (a paid booking cannot go back). { type: 'restart' } gives seats. Any other type throws an Error whose message is Unknown action: and the type.
BookingSteps, the default export, keeps the step with useReducer and bookingFlow, starting at seats. It shows a heading, h2: Step 1 of 4: Pick your seats (then Step 2 of 4: Your details, Step 3 of 4: Pay and Step 4 of 4: Booked, with the titles the starter gives). On steps 1 to 3 it shows a Back button, disabled on step 1, which sends back, and a Next button, which says Pay on step 3, which sends next. On step 4 only it shows a paragraph, Your tickets are booked., and a Book again button, which sends restart, and no Back button. The buttons only send actions: the Check calls bookingFlow on its own, then clicks through every step.
- Task 3
Basket.jsx: the snack basket, wired to the reducer
Make Basket keep the basket with useReducer and cartReducer from cart.js, starting empty, []. It shows a heading, h2, Snacks, then a list with one item per snack in snacks.json, each with the snack's name, its price (₹150) and a button Add and the snack's name (Add Popcorn), which sends { type: 'add', item: snack }.
Then a heading, h2, Your basket. When the basket is empty, a paragraph: Your basket is empty. Otherwise a list with one item per line, each showing the name and the qty as Samosa × 2, the line's price times its qty as ₹80, and three buttons named for the snack: One less Samosa, which sends { type: 'setQty', id, qty } with one less; One more Samosa, which sends add; and Remove Samosa, which sends { type: 'remove', id }. Under that list, a paragraph Total: ₹110 (every line's price times qty, added up) and a button Clear basket, which sends { type: 'clear' }. A button that shows only − or + gets its name from aria-label="One less Samosa".
Basket changes the basket only by sending actions to cartReducer. The Check gives Basket its own cart.js, so this task does not depend on Task 1, reads the actions you send, and also gives it another snacks.json (Bhel ₹60, Filter coffee ₹45).
- Task 4 · interview question
Interview: GroupTickets.jsx, the total that drifted
The group tickets box keeps three pieces of state with useState, and two of its five handlers forget the total: three tickets, then Balcony, still says Pay ₹540, and Start again leaves the old total. Fix it by moving every change into one reducer: keep the state with useReducer, with no useState left in GroupTickets.jsx, and make each button send an action.
The page shows a heading, h2, Group tickets; three buttons, Front ₹120, Middle ₹180 and Balcony ₹240, from prices, where the chosen one has aria-pressed true (Middle at the start); a paragraph Tickets: 3; a button Add a ticket, disabled at 10 tickets, and a button Remove a ticket, disabled at 0; a button Pay ₹720, the tickets times the chosen class's price, disabled at 0 tickets; and a button Start again, which goes back to 0 tickets and Middle.
Keep the line const prices = { Front: 120, Middle: 180, Balcony: 240 }; as it is: the Check also changes Balcony's price to 300, and then three Balcony tickets must say Pay ₹900.
Rukhsana will ask: when would you pick useReducer over useState?
What you will learn
- A reducer: a plain function, (state, action) => next state, that holds every rule for a piece of state.
- Actions: plain objects that say what happened, like { type: 'closed' }.
- useReducer(reducer, initial): the state, and a dispatch function that sends actions.
- What dispatch does inside: React calls your reducer on the next render, and shows what it returns.
- Pure reducers: StrictMode calls a reducer twice to catch one that changes its state.
- Unknown actions: a reducer throws on a type it does not know.
- useState or useReducer: how to choose.
More in State
Build "Reducers, every change in one place" yourself
Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. 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 are free. This one comes with the all labs plan.