Sub topic 2
Using `useReducer` and `dispatch` in a Component
This chapter assumes you know JavaScript functions, objects, arrays, JSX, React function components, useState, props, and event handlers.
Using `useReducer` and `dispatch`
useReducer stores state whose updates follow several related rules. A reducer is a pure function that receives the current state and an action, then returns the next state. An action is an object describing what happened. dispatch sends an action to the reducer.
import { useReducer } from 'react';
function counterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export default function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>
<button onClick={() => dispatch({ type: 'decremented' })}>-1</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}The component handles user events. The reducer handles state-transition logic. React calls the reducer with the current state and dispatched action, then renders with the returned state.
Keeping reducers pure
A pure reducer:
- Does not mutate
state. - Does not call APIs, timers, or browser APIs.
- Does not produce random values.
- Returns the same result for the same state and action.
Put side effects such as fetching data in an event handler or useEffect. Dispatch actions such as fetch_started and fetch_succeeded to record their results.
`useState` or `useReducer`?
Use useState for a small, independent value. Use useReducer when several fields change together or many events update the same state.
| Choose | When |
|---|---|
| `useState` | A value has a few simple updates |
| `useReducer` | State transitions are related and benefit from named actions |
Exercise
What should the reducer return for { type: 'incremented' } when the current state is { count: 2 }?
Show answer
It should return a new object, { count: 3 }, without changing the original state.