Redux Reducer: Making the actions work

Redux Reducer: Making the actions work

Till the last blog, we were aware of the actions in Redux. But, in redux, actions alone can't do the job. You need the other elements to come and join the hand together to make the redux work. Let's see how the flow works ahead of actions. (If you haven't read the previous blog, read here )

Dispatch

As the English of this word says, dispatch is a way to get something done from the actions. Whenever you need to call a function from the action, you need to dispatch it. Dispatching an action makes it available to other parts of Redux to take and modify as they are needed to. Though most of the functioning takes place in actions themselves, it must be dispatched to get it to work.

An action must be dispatched at two places in an application. One, inside the action and the other in the part where the action is called. The code looks like this:-

// In action.js

function test(){

   dispatch({type: TEST_USER, payload: user});
}

// In Component1.js at the end of the file

mapDispatchToProps = (dispatch) => {
   test: () => dispatch(test());
}

As it can be deduced from the name mapDispatchToProps, it can be inferred that by this function, actions are mapped with props. These props will then change as per the action.

Reducer

Reducer is the place where all the final states are collected before sending them to the store. Though we can update the state in the reducer itself, doing it in action is more convenient. Reducers manage all the new and old states as per the dispatched action. It will see what the action demands and modify the states as per the action.

A reducer has a switch case to handle different state updates. The common way to write a reducer is as follows.

export default (state = defaultState, action) => {
  switch (action.type) {
    case ABC:
        // details about action and payload
    case XYZ:
       // details about action and payload
   }
}

After the reducer updates the state, it is sent to the Store. To know more about Store and other remaining parts of the redux, you shall wait for the next blog. Comment about how you felt about the blog.