Sitemap

How to use useReducer in React JS Part 2 (with object)

3 min readOct 15, 2025

--

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:

  1. initialState → the starting value
  2. count → the current value (state that updates over time)
  3. reducer → the rulebook (how the value should change)
  4. 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 sets count equal to initialState.
  • Example:
  • const initialState = 0; const [count, dispatch] = useReducer(reducer, initialState);
  • 🔹 At this moment → count = 0.
  • After you start sending actions with dispatch,
    the reducer updates count again and again.
    But the first time, React always starts from initialState.

🧠 In short:

initialState is the starting point.
count is the current point.

So:

  • When the component first renders → count = initialState
  • Later on → count changes based on what the reducer returns

⚙️ Relationship 2: dispatch ↔️ reducer

💡 Think of this as “the messenger and the rulebook.”

  • dispatch is the function you call when you want to change something.
  • But dispatch itself doesn’t know how to change the value —
    it simply sends your message (called an action) to the reducer.

Here’s what happens step by step:

  1. You call:
  • dispatch({ type: "increment" });
  1. React automatically calls your reducer function like this:
  • reducer(currentState, { type: "increment" });
  1. The reducer looks at the action.type and returns a new state (new value).
  2. React updates count with whatever the reducer returns.

So, the link is:

dispatch tells React to run the reducer.
The reducer decides what the new count should 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 😊

--

--