Skip to content

Another way of writing Reducer in StateManagement

Last updated on May 6, 2020

In this blog post, you will learn another way of writing reduxReducerfunction piece of State Management for front-end applications.

Introduction

If you have used reduxfor your front-end application to apply state management techniques, then you must have come across this one.

As normally, we use Switchsyntax to write the Reducerpiece of code. Reducerwill help you to update the State(single source of truth) of the application.

You will learn what’s an alternate approach we have to implement Reducerfunction.

Another way of writing Redux-Reducer in StateManagement

WHY I emphasize this point here is that, writing the code that really works finally matters. But to keep code readablethat will help us in the long term maintaining the code-base.

For instance, to understand this piece will take up some code snippets along with the explanation.

You have almost used some sort of authentication where you have loginand logoutmethods. You trigger those methods with Actiondispatching.

Once the action is dispatched from the UI component, that will get routed to Reducerwhere the application state is maintained.

Our simple state representation of an object would be,

const initialState = {
  is_loggin_in: false,
  is_logged_in: false,
  user: {}
};

1. Switch Syntax,

export const authReducer = (state = initialState, action) => {
  switch (action.type) {
    case LOGGING_IN:
      return {
        ...state,
        is_loggin_in: true
      };
    case LOGGED_IN:
      return {
        ...state,
        is_loggin_in: false,
        is_logged_in: true,
        user: action.payload
      };
    case LOGGED_OUT:
      return {
        ...state,
        is_loggin_in: false,
        is_logged_in: false,
        user: null
      };
    default:
      return {
        ...state
      };
  }
};

authReduceris the function name to update Statewith the Switchsyntax.

2. Object Lookup,

The same authReducerfunction you can re-write by having Object Look-upway.

you have totally 3 cases from the above function, that you can have as a property of an object.

const authLookup = {
  [LOGGING_IN]: {
        ...state,
        is_loggin_in: true
  },
  [LOGGED_IN]: {
        ...state,
        is_loggin_in: false,
        is_logged_in: true,
        user: action.payload
  },
  [LOGGED_OUT]: {
        ...state,
        is_loggin_in: false,
        is_logged_in: false,
        user: null
  }
}
export function authReducer = (state= initialState, action) => {
  return authLookup[action.type] || state;
}

Now you might have noticed the huge difference, how we refactored our code that helps on code readability.

We have used Computedproperty from JavaScript ES6 to dynamically evaluate the property name for action type that will return you the updated state.

Published inAngularFrameworksJavaScriptReact