Redux Bad Practices #2: Duplicate Code

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:

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.

--

--

http://adamklein.dev/ I write code, and speak about it

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store