useReducer is like useState, but in a more organized form.
With useState, you update the state directly—for example, by calling setCounter(counter + 1).
With useReducer, you don’t change the state yourself. Instead, you send an instruction, and a separate function decides how the state should be updated.
It consists of three parts:
-
The state: This is your data—e.g.,
{ counter: 0 }. -
The
dispatch: This acts as a button that sends an instruction—e.g.,dispatch({ type: 'INCREMENT' }). You simply specify "what should be done." -
The reducer: This is the "boss." It’s a function that takes the current state and the instruction, then returns the new state.
// The boss
function reducer(state, action) {
if (action.type === 'INCREMENT') {
return { counter: state.counter + 1 };
}
if (action.type === 'DECREMENT') {
return { counter: state.counter - 1 };
}
return state;
}
// Inside your component
const [state, dispatch] = useReducer(reducer, { counter: 0 });
When should you use it?
useStateis sufficient for 90% of cases—like handling a boolean or an input field.
useReducerbecomes useful when:
your state is a complex object;
there are many different ways to modify it;
the next value depends on the previous one.
In short:useStatemeans "set this value," whileuseReducermeans "here is what happened—figure out how to update the state accordingly."

Posted Using INLEO