useState vs useReducer
- React course
- Beginner
- Lesson 63/84
- 4 min
Learn when to prefer useReducer over useState.
useState vs useReducer
Which one you choose depends on state complexity. For a single number or string useState is enough; for several related fields or many transitions useReducer is cleaner.
useReducer gathers logic in one place; you can test it without the component. useState needs fewer lines and fewer concepts.
Both are equally fast; the choice is about readability.
Transition table
The power of useReducer is that transitions read like a table. Each action type produces a new state; this makes debugging easy.
In useState the logic spreads across handlers; finding a bug means looking at several functions.
Later libraries like Redux will extend the same reducer model; learning the base here matters.
Practice Two-way counter
Complete the skeleton. Write a reducer function; in switch(action.type) have case "up": return state + 1;, case "down": return state - 1; and default: return state;. Write a Counter component; import useReducer, define const [state, dispatch] = useReducer(reducer, 0);. Return <button onClick={() => dispatch({type: "up"})}>{state}</button>. Export it.
Starter code
import { useReducer } from "react";
// Define reducer and Counter hereSample solution
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "up": return state + 1;
case "down": return state - 1;
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, 0);
return <button onClick={() => dispatch({ type: "up" })}>{state}</button>;
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Best choice for several related fields and many transitions?
useReducer collects logic in one place.- useReducer Correct answer
- useRef
- useState
- a prop
Explanation: useReducer gathers complex transitions.
2 useState vs useReducer: fill in the missing part
const [count, setCount] = ____(0);
const [count, setCount] = useState(0);
Explanation: useState is enough for a simple counter.
3 useState vs useReducer: match the terms
| Term | Meaning |
|---|---|
useState |
Simple state |
useReducer |
Complex state |
dispatch |
Sends an action |
reducer |
Pure function |