DEV Community

loading...

Getting started with useReducer Hook!

Jayant Khandelwal
Software Developer || Ex- NodeJS Mentor @ GirlScript
・2 min read

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.

Alt Text

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.

reducer fnction

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.

Alt Text

let's have a look at the complete code:

complete

Following is the output for the above code,

output

We will see two more ways to use useReducer hook in the upcoming posts.
Stay Tuned!

Happy Coding!

Thank you!

-Jayant Khandelwal

Discussion (0)