Redux Bad Practices: Duplicate Code

Adam Klein

Many applications have repeating functionality for different reducers with minor changes. For example, many forms that have view and edit modes.

bad approach would be to duplicate the reducer code:

function userFormReducer(state, action) {
  switch (action.type) {
    case SET_USER_VIEW_MODE:
       return { ...state, viewMode: action.payload.viewMode };
    ...
  }
}

function jobFormReducer(state, action) {
  switch (action.type) {
    case SET_JOB_VIEW_MODE:
       return { ...state, viewMode: action.payload.viewMode };
    ...
  }
}

function companyFormReducer(state, action) {
  // you get the point...
}

good approach would be to delegate the work to a dedicated reducer, that saves viewMode per form name:

function formReducer(state, action) {
  switch (action.type) {
    case SET_VIEW_MODE:
       return {
         ...state,
         [action.payload.formName]: { viewMode: action.payload.viewMode }
       };
    ...
  }
}

There are a few patterns for doing this:

  • Extract repeated reducer logic to a dedicated reducer like in the example above;
  • Use a higher-order reducer for similar reducer functionality;
  • Use middleware if your use-case justifies that. For example, if you repeat similar code for many types of actions.

Keep it DRY (don’t repeat yourself). Taking the time to think how to re-use code, almost always proves to be efficient in the long run. Don’t be lazy, it’s worth the while!

Popular