useState vs useReducer
Both hooks manage local state, but for different scenarios.
useState
tsx
const [count, setCount] = useState(0);
setCount(count + 1);Best for simple, independent values.
useReducer
tsx
type Action = { type: 'increment' } | { type: 'reset' };
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'increment': return state + 1;
case 'reset': return 0;
}
}
const [count, dispatch] = useReducer(reducer, 0);
dispatch({ type: 'increment' });When to use useReducer
- State is an object with several interrelated fields.
- Next state depends on previous state.
- Complex state transition logic.
- You want to isolate business logic and cover it with tests.
useReducer+Contextis a lightweight alternative to Redux for medium-sized apps.
updated
did you know it?