useReducer
Managing complex state with actions and a reducer function
Skills taught: react.useReducer, react.reducer-pattern, react.dispatch, react.action-types
useReducer pattern
// Counter with useReducer — actions describe WHAT happened, reducer decides HOW state changes
const initialState = { count: 0, step: 1, history: [] };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + state.step, history: [...state.history, `+${state.step}`] };
case 'decrement':
return { ...state, count: state.count - state.step, history: [...state.history, `-${state.step}`] };
case 'reset':
return { ...initialState };
case 'setStep':
return { ...state, step: action.payload };
default:
return state; // unknown actions return current state unchanged
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px' }}>
<h2>Count: {state.count}</h2>
<p>Step: {state.step}</p>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '8px' }}>
<button onClick={() => dispatch({ type: 'increment' })}>+{state.step}</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-{state.step}</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
<label>
Step: <input
type="number" min="1" max="10" value={state.step}
onChange={e => dispatch({ type: 'setStep', payload: Number(e.target.value) })}
style={{ width: '50px', padding: '4px' }}
/>
</label>
<p style={{ fontSize: '0.8rem', color: '#6b7280' }}>History: {state.history.join(', ') || '—'}</p>
</div>
);
}
function App() {
return <Counter />;
}
Frequently Asked Questions
When should I use useReducer instead of useState?
Three indicators: (1) You have multiple setX calls in a single event handler that update related state together — these belong in one reducer action. (2) The new state depends on multiple current state fields. (3) You want the state update logic to be testable without mounting a component (just call reducer(state, action) in a test).