Rewrite a counter so that its buttons dispatch actions to a reducer.
What to build
A counter managed by useReducer.
Requirements
- Write
counterReducerhandling the actionsincremented,decremented(never below 0) andreset, and throwing for any other type. - Show the count in a
pwith the idcount; the buttons+,-andResetdispatch the three actions.
Constraints
Use useReducer, not useState.
Example
- three times, - once, shows 2; Reset shows 0; - at 0 stays 0.
Why it works
The buttons only say what happened, and every rule about the count, including never going below 0, lives in one pure function.
Hints
Hint 1
function counterReducer(count, action) { switch (action.type) { ... } }
Hint 2
const [count, dispatch] = useReducer(counterReducer, 0);
Solution
Show one correct solution (try it yourself first)
import { useReducer } from "react";
function counterReducer(count, action) {
switch (action.type) {
case "incremented":
return count + 1;
case "decremented":
return Math.max(0, count - 1);
case "reset":
return 0;
default:
throw new Error("Unknown action: " + action.type);
}
}
export default function App() {
const [count, dispatch] = useReducer(counterReducer, 0);
return (
<div>
<p id="count">{count}</p>
<button onClick={() => dispatch({ type: "incremented" })}>+</button>
<button onClick={() => dispatch({ type: "decremented" })}>-</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}