useReducer
Actions and a reducer.
As state logic grows, the updates get scattered across many event handlers. A reducer collects them in one place. Handlers just describe what happened, as an action.
- Updates everywhere
- One place
- Actions
A reducer counter
The reducer takes the current state and an action, and returns the next state. Each action has a type, like add or remove. Use reducer gives us the state, and a dispatch function. Buttons dispatch actions, instead of setting state directly. We add three, and remove one. Run it.
import { useReducer } from "react";
function reducer(count, action) {
switch (action.type) {
case "add": return count + 1;
case "remove": return Math.max(0, count - 1);
default: throw new Error("Unknown action " + action.type);
}
}
export default function App() {
const [count, dispatch] = useReducer(reducer, 0);
return (
<div className="box">
<p>Helmets: {count}</p>
<button id="add" onClick={() => dispatch({ type: "add" })}>Add</button>
<button id="rm" onClick={() => dispatch({ type: "remove" })}>Remove</button>
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#add", "times": 3}, {"click": "#rm"}]How it flows
A click dispatches an action. React calls the reducer, with the current state and that action. The reducer returns the new state. And the component renders with it.
- Click
- dispatch(action)
- reducer(state, action)
- New state
- Render
Reducer rules
A reducer must be pure. Same inputs, same output, no side effects. Never change the state, return a new one. And keep it outside the component, so it's easy to test.
| key | value |
|---|---|
| Pure | no side effects |
| Return | new state |
| Never | change state |
| Lives | outside the component |
Summary
Use reducer moves update logic into one pure function, driven by actions. Next, reducers with context.
Key takeaways- dispatch({ type })
- reducer(state, action)
- Pure