Redux Bad Practices #2: Duplicate Code

Adam Klein
1 min readFeb 27, 2019

--

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

One 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) { etc...}

A better approach would be to delegate the work to a dedicated reducer, that saves viewMode for each form:

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!

Originally published at 500tech.com.

--

--

Adam Klein
Adam Klein

No responses yet