DEV Community


useReducer (The Intermediate):

jackent2b profile image Jayant Khandelwal ・2 min read

Welcome back devs!

We have talked about useReducer hook, its usage, and its implementation in the previous post of this series.

Now in this post, we will make use of useReducer in a slightly complex manner.

First of all let us have a recap,


action: Action is a plain JavaScript string or object that contains information. Actions tell the reducer what kind of action to perform and all other fields contain information or data.

initialState: defines the initial state of the component.

currentState: defines the current state of the component

reducer: reducer() function accepts the currentState and action and then returns a new state based on that action

useReducer hook returns the currentState and the dispatch method.

dispatch: dispatch method is capable of accepting an action to execute the code specified in the render function i.e. it accepts the action and transfers it to the reducer function.

Note: initialization of initialState and reducer() is always made outside the functional component.

First of all, let's initialize our initialState and implement our reducer function as follows:

Alt Text

You can see that this time we have two states to maintain that is firstCounter and secondCounter. So, in order to maintain two states, we have used an object to initialize the state.

We have used spread operator because useReducer does not automatically merge and update the object i.e. useReducer does not merge the state automatically.

Now let's take a look at the functional component,
Functional Component

Here we have passed action as an object. We generally pass action as an object when we have more than one property to be accepted by the reducer function.

As here we are maintaining two states, therefore we are sending two different type property (eg: increment and increment2) for
firstCounter and secondCounter respectively.

Let's have a complete look at the code,
Alt Text


Alt Text

We will see one more way to use the **useReducer* hook in the upcoming posts of this series.*

Stay Tuned!

Happy Coding!

Thank you!

-Jayant Khandelwal

Discussion (0)

Editor guide