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 馃嵒 !
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 :)
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.