How to use useReducer hooks in ReactJS

In javascript, we use reducer. reducer is generally very simple to use that return a single value. reducer mainly has two params. one is callback and another is initial value.

const sum = [1,2,3].reduce((acc, curr) => acc+curr, 0);

The power of useReducer is well-documented. It is the fundamental building block of all state management in React Hooks, so ultimately any hook-based state management depends on it. But it's worth asking, is it the best API we could come up with? One must admit that it forces us to write our logic in a fairly awkward style.

Let's take a look at a small example. The Counters component renders a list of counters, each of which you can either increment or clear, and a button to add a new counter at the end. useReducer has also dispatch as well to set the value inside variable syntax is like

const [state, dispatch] = useReducer(reducerFunction, initialValues);

let's introduce the commonly use variable.

State: This is the final state that is changed by any dispatching the actions

Initial Values: As per it name it is the initial value and it is generally object

const initialValues = { count: 0 };

Reducer Function: All the dispatch-able function and also mutation of state is happening inside the reducer function. Also the complex logic written inside the reducer function

/**
* generally action has only type 
* also we can send payload with action type
* typeof action is {type: String, payload: any}
*/
function reducerFunction(state, action) {
  switch(action.type){
    case 'INCREMENT': {
      state.count = state.count + 1;
      return state;
    }
    case 'DECREMENT': {
      state.count = state.count - 1;
      return state;
    }
    case 'SET_VALUE': {
      state.count = action.payload.value;
      return state;
    }
    default: {
      return state;
    }
  }
}

Dispatch: Dispatch is a method that is used to mutate the object using reducer function.

function someFunc(){
  dispatch({
    type:'INCREMENT',
   // payload: {} we can pass the payload if required
  })
}

function someAnotherFunc(){
  dispatch({
    type:'SET_VALUE',
    payload: {value: 5}
  })
}

Write a comment ...