- Home
- /
- Tutorials
- /
- React Tutorial
- /
- useReducer Explained
State and Reducers
useReducer Explained
A reducer is a pure function from the current state and an action to the next state. All the transition logic ends up in one place you can read top to bottom.
The shape
useReducer(reducer, initialState) returns the current state and a dispatch function. Components describe what happened; the reducer decides what that means.
A counter as a reducer
jsx
function reducer(state, action) {
switch (action.type) {
case "increment": return { count: state.count + 1 }
case "decrement": return { count: state.count - 1 }
case "reset": return { count: 0 }
default: return state
}
}
function Counter() {
const [state, dispatch] = React.useReducer(reducer, { count: 0 })
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "decrement" })}>−</button>{" "}
<button onClick={() => dispatch({ type: "increment" })}>+</button>{" "}
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Counter />)