React-redux-starter-kit: [QUESTION]: Why use action handlers instead of a switch/case statement

Created on 20 Jan 2017  路  2Comments  路  Source: davezuko/react-redux-starter-kit

Hi guys, This could be a pretty dummy question but cant figure out which one to use.

Is there any special reason to use actions handlers+reducer instead of a switch/case statement inside the reducer?

For example, in the counter reducer /src/routes/Counter/modules/counter.js there is:

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [COUNTER_INCREMENT]    : (state, action) => state + action.payload,
  [COUNTER_DOUBLE_ASYNC] : (state, action) => state * 2
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = 0
export default function counterReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}

Why is that better than use the following code?

const initialState = 0
export default function counterReducer (state = initialState, action) {
  switch (action.type) {
    case COUNTER_INCREMENT:
      return state + action.payload
    case COUNTER_DOUBLE_ASYNC:
      return state * action.payload
    default:
      return state
  }
}

Thanks so much in advise 馃嵒 !

Most helpful comment

It's not better, just a different style. Switch statements allow you to fall through for multiple actions types so they can be handled the same way without duplication, whereas that would be slightly more verbose with the object lookup style. It does slightly reduce boilerplate for the majority of use cases, at least in my opinion, but there really isn't a huge reason why you should prefer one over the other besides personal preference. Hope that helps.

All 2 comments

It's not better, just a different style. Switch statements allow you to fall through for multiple actions types so they can be handled the same way without duplication, whereas that would be slightly more verbose with the object lookup style. It does slightly reduce boilerplate for the majority of use cases, at least in my opinion, but there really isn't a huge reason why you should prefer one over the other besides personal preference. Hope that helps.

Yeap, that has cleared up my mind! Thanks mate :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nickgnd picture nickgnd  路  4Comments

dfalling picture dfalling  路  5Comments

postalservice14 picture postalservice14  路  4Comments

rpribadi-ds picture rpribadi-ds  路  5Comments

gilesbradshaw picture gilesbradshaw  路  5Comments