Redux Bad Practices: Duplicate Code
Last updated on Nov 27, 2017

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

A 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...
}

A 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 other options as well:

  • 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!

Back to all articles
We are leading front-end consultancy specializing in React, React Native, and Angular. We build web and mobile apps, train teams and consult on complex projects.

Tel AvivIsrael

New York CityUSA

© 500Tech. Building high-quality software since 2012.