How to use useReducer in React JS Part 2 (with object)
In part 1, we have seen the basic use of useReducer. In this part, we will see more advanced use of useReducer, where we can use objects
Get Ridoyzzaman’s stories in your inbox
Join Medium for free to get updates from this writer.
Defining object
const initialState={
counter: 0
}const [count, dispatch ] =useReducer (reducer, initialState)There are four key pieces involved here:
initialState→ the starting valuecount→ the current value (state that updates over time)reducer→ the rulebook (how the value should change)dispatch→ the messenger (sends actions to the reducer)
Now, let’s see how they relate step by step 👇
🧩 Relationship 1: count ↔️ initialState
💡 Think of this as “the past and present of your state.”
- When the app (or component) first starts,
React setscountequal toinitialState. - Example:
const initialState = 0; const [count, dispatch] = useReducer(reducer, initialState);- 🔹 At this moment →
count=0. - After you start sending actions with
dispatch,
the reducer updatescountagain and again.
But the first time, React always starts frominitialState.
🧠 In short:
initialStateis the starting point.
countis the current point.
So:
- When the component first renders →
count = initialState - Later on →
countchanges based on what thereducerreturns
⚙️ Relationship 2: dispatch ↔️ reducer
💡 Think of this as “the messenger and the rulebook.”
dispatchis the function you call when you want to change something.- But
dispatchitself doesn’t know how to change the value —
it simply sends your message (called an action) to thereducer.
Here’s what happens step by step:
- You call:
dispatch({ type: "increment" });
- React automatically calls your reducer function like this:
reducer(currentState, { type: "increment" });
- The
reducerlooks at theaction.typeand returns a new state (new value). - React updates
countwith whatever thereducerreturns.
So, the link is:
dispatchtells React to run thereducer.
Thereducerdecides what the newcountshould be.
We need to define the reducer function before as below
const initialState={
counter: 0
}
const reducer =(state, action)=>{
switch(action.type){
case 'increment':
return {counter:state.counter + 1};
}
case 'decrement':
return {counter:state.counter - 1};
}
default:
return state;
}
};
const [count, dispatch ] =useReducer (reducer, initialState)JSX
return (
<div>
<button onClick={() => dispatch({ type: "increment" })}>+</button>{" "}
<span>{count.counter}</span>{" "}
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);Happy Learning 😊








