DEV Community

SavvyShivam
SavvyShivam

Posted on

useReducer in React

useReducer is basically an alternative to useState hook.
useReducer is used to manage the states of the application. The state reducer pattern enables us to properly manage our state’s updates based on criteria that the user provides

useReducer accepts two arguments :

  1. Reducer

  2. Initial state

And returns the following :

  1. Current state

  2. Dispatch

Reducer

A Reducer is a pure function that takes in a current state and objects returning what the user did, called actions and returns a new state.
Initial State: As the name suggests, it is the value that the user has provided in the initial phase of the state
Current state: It represents the current state.
Dispatch: This is a function used to update the state by calling the action object.

How to import useReducer:

To import the useReducer Hook we use the following code in the top level of the code

Using useReducer:

The syntax for using useReducer is given as follows :

Here, we are trying to create a counter.
Here the currentState will be a variable that will keep a record of the current count of the number.
Dispatch will let us change the state in response to interaction i.e. when we click the button, an onClick event including the dispatch function will occur.

React will pass the current state and the action to your reducer function. Your reducer will calculate and return the next state. React will store that next state, render your component with it, and update the UI.
Here the reducer function takes in two arguments, state, and action. The switch statement is generally used, by convention, for carrying out the calculations and returning the next state.

Here, we have used two cases : “increment_number” and “decrement_number” which adds 1 and subtracts 1 from the current state variable respectively and returns it.

Lastly, we define the initial state of the counter,

In the return function, we create two button tags where in the onClick eventHandler we call the dispatch function **and then **specify the type. “increment _number” for the increment button and “decrement_number for the decrement button.

You can find the entire working code in the following code sandbox link:
https://codesandbox.io/s/use-reducer-tt2unh

Top comments (0)