useReducer Hook is also used for state management!
-> It is an alternative to useState (useState is built using useReducer)
-> What's the difference between the two?
-> When to useReducer v useState?
Have you ever came across the reduce() function in JavaScrpt?
Let us make a contrast between reduce and useReducer hook.
Syntax
-> reducer(currentState,action)
-> useReducer(reducer,initialState)
Roles
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.
Now, let us have a look at our code!
First of all, let's make the reducer() function and initialize an initialState.
Note: initialization of initialState and reducer() is always made outside the functional component.
Now let's make use of the useReducer hook.
Call a useReducer hook inside the functional component and pass reducer and initialState as arguments in it.
let's have a look at the complete code:
Following is the output for the above code,
We will see two more ways to use useReducer hook in the upcoming posts.
Stay Tuned!
Happy Coding!
Thank you!
-Jayant Khandelwal
Top comments (2)
This blog is really helpful!!
Glad to know that it helped you!