useReducer hook in React we use for state management

It is an alternative of useState and also preferable while write complex state logic also it helps you to improve performance of React application

useState is built using useReducer

Example of useReducer

In the above example, you can see we create one reducer function with two arguments (1) state (2) action and the reducer function must return updated state

Here the argument state contains value of previous state.

And action is object which can help to you to change state value with condition.

As compare to useState, useReducer more preferable while we have complex logic or state value we want handle.

Next, you can notice inside the CounterReducer component we use useReducer which has two arguments (1) reducer function (2) initial state

useReducer function returns an array with two values (1) state (2) dispatch where state contains update data of state and dispatch is a function which can help to reach reducer.

You can see we write dispatch(‘increment’) on button’s click event means when we call dispatch React internally link it to our reducer function and here ‘increment’ will pass to action.

So that action will get compare with switch case inside reducer and accordingly updated state will get a return and our component re-render with the new value.

Complex State and Action with useReducer Example

In the above example you can see state and action both are objects not only string or int so while dispatching action we need to pass object.

const initialState = {
    firstName : '', lastName : '', age : 0

We are getting two values with action object (1) type (2) value, so when we change firstName, lastName or age we call dispatch function with an object which has type and value both and that object will be received in reducer function action argument.


Here triple dot state (…state) inside reducer function is spread operator which can help you to get copy of previous value from state object and then you can change only field that you want to.

return { ...state, firstName: action.value }

useReducer with useContext

useContext if you are not aware about then please check my useContext post first then continue useReducer here.




Related Posts

Leave a Reply