Modelling state with a reducer
A counter that can increment, decrement, and reset is three setters, each with its own rule. Add a fourth action and those rules spread further apart, until no single place says how the count can change.
useReducer replaces the pile of setters with one reducer — a plain function
that takes the current state and an action, and returns the next state:
function reducer(count, action) {
switch (action) {
case 'increment':
return count + 1;
case 'decrement':
return count - 1;
case 'reset':
return 0;
}
}
The hook returns the current state and a dispatch function:
const [count, dispatch] = useReducer(reducer, 0);
You never call the reducer yourself. You dispatch an action, React calls the
reducer with the current state and that action, and re-renders with whatever it
returns:
<button onClick={() => dispatch('increment')}>Increment</button>
Every transition now lives in one function, so the ways the state can change are
listed in one place. Adding an action means adding a case, not another setter.
The reducer is also pure: the same state and action always give the same next
state.
Your job is to model a counter with useReducer in App.jsx.
Challenge
A counter needs three controls — add, subtract, reset — and one place that
decides how each changes the count. Export an App component from App.jsx
that keeps a count in useReducer, starting at 0, and renders it in a <p>
element as Count: <n>. Render three buttons labelled Increment, Decrement,
and Reset, each dispatching the matching action.
The Test clicks increment, decrement, reset, then increment again, and expects
the paragraph to read Count: 1. The starter renders a fixed count and never
dispatches, so the Test fails.