Model transitions with useReducer
Describe the next state with a reducer
A reducer is a function that receives the current state and an action describing an event, then calculates the next state. useReducer connects that function to a component. It is useful when several events must follow the same rules. The examples below are separate App.jsx files for the Chapter 3 client project, with expected visual outcomes pending browser verification.
import React, { useReducer } from 'react';function seatReducer(count, action) { switch (action.type) { case 'reserved': return Math.min(4, count + 1); case 'released': return Math.max(0, count - 1); case 'reset': return 0; default: throw new Error('Unknown seat action'); }}export default function App() { const [count, dispatch] = useReducer(seatReducer, 0); return <main><h1>Workshop seats</h1><p>Reserved: {count} of 4</p> <button disabled={count === 4} onClick={() => dispatch({type: 'reserved'})}>Reserve</button> <button disabled={count === 0} onClick={() => dispatch({type: 'released'})}>Release</button> <button onClick={() => dispatch({type: 'reset'})}>Reset</button></main>;}The display starts at zero. Reserve increases it, Release decreases it, and Reset returns it to zero. The reducer enforces limits independently of disabled buttons, so repeated actions cannot exceed capacity. Action names describe events; type is a convention, not a required React property. Throwing for unknown actions is an explicit choice to expose programmer mistakes.
Initialize state from an input
import React, { useReducer } from 'react';function makeDraft(title) { return { title: title.trim(), seats: 1 }; }function draftReducer(state, action) { if (action.type === 'titleChanged') return {...state, title: action.title}; if (action.type === 'reset') return {title: action.title.trim(), seats: 1}; throw new Error('Unknown draft action');}export default function App() { const [draft, dispatch] = useReducer(draftReducer, ' Clay workshop ', makeDraft); return <main><label htmlFor="draft-title">Workshop title</label> <input id="draft-title" value={draft.title} onChange={e => dispatch({type:'titleChanged', title:e.target.value})} /> <p>Seats: {draft.seats}</p> <button onClick={() => dispatch({type:'reset', title:'Clay workshop'})}>Reset</button></main>;}The Hook accepts the reducer, an initial argument, and optionally an initializer function. With an initializer, the starting state comes from its return value. Later changes to the initial argument do not automatically reset existing state. An explicit reset event expresses that intent. Both functions must be deterministic and free of effects; development StrictMode may call them an extra time and discard one result.
Choose the simplest state tool
import React, { useState } from 'react';export default function App() { const [details, setDetails] = useState(false); return <main><button aria-expanded={details} onClick={() => setDetails(v => !v)}>Details</button> {details && <p>Bring a reusable apron.</p>}</main>;}This independent Boolean needs only useState. A reducer adds value when the transitions form a domain policy or multiple events update related fields. Neither choice makes state global. Keep it with the closest owner. Practice: predict the counter after six reserve events, one release, and reset. Explain why the reducer still guards the upper limit.