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,
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:
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.
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.
We will see one more way to use the **useReducer* hook in the upcoming posts of this series.*