Why to use switch case in reducer?

Asked by At

I wonder what are the advantages of using switch case syntax in reducer instead of e.g. object mapping syntax? I didn't meet yet any example that uses another statement than switch case, and I wonder why there are no alternatives for that. Please describe your thoughts about the advantages and disadvantages of both ways (only if they are justified).

const initialState = {
  visibilityFilter: 'SHOW_ALL',
  todos: []
};

// object mapping syntax
function reducer(state = initialState, action){
  const mapping = {
    SET_VISIBILITY_FILTER: (state, action) => Object.assign({}, state, {
      visibilityFilter: action.filter
    }),
    ADD_TODO: (state, action) => Object.assign({}, state, {
      todos: state.todos.concat({
        id: action.id,
        text: action.text,
        completed: false
      })
    }),
    TOGGLE_TODO: (state, action) => Object.assign({}, state, {
      todos: state.todos.map(todo => {
        if (todo.id !== action.id) {
          return todo
        }

        return Object.assign({}, todo, {
          completed: !todo.completed
        })
      })
    }),
    EDIT_TODO: (state, action) => Object.assign({}, state, {
      todos: state.todos.map(todo => {
        if (todo.id !== action.id) {
          return todo
        }

        return Object.assign({}, todo, {
          text: action.text
        })
      })
    })
  };
  return mapping[action.type] ? mapping[action.type](state, action) : state
}

// switch case syntax
function appReducer(state = initialState, action) {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER': {
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    }
    case 'ADD_TODO': {
      return Object.assign({}, state, {
        todos: state.todos.concat({
          id: action.id,
          text: action.text,
          completed: false
        })
      })
    }
    case 'TOGGLE_TODO': {
      return Object.assign({}, state, {
        todos: state.todos.map(todo => {
          if (todo.id !== action.id) {
            return todo
          }

          return Object.assign({}, todo, {
            completed: !todo.completed
          })
        })
      })
    }
    case 'EDIT_TODO': {
      return Object.assign({}, state, {
        todos: state.todos.map(todo => {
          if (todo.id !== action.id) {
            return todo
          }

          return Object.assign({}, todo, {
            text: action.text
          })
        })
      })
    }
    default:
      return state
  }
}

1 Answers

2
jsdeveloper On

There are no advantages of switch statements in reducers (that I know of) other than that they are idiomatic/standardised and may help other people understand your code.

Personally, I've switched to non-switch reducers.