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:
- 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!
All articles in this series:
https://medium.com/@adamklein_66511/redux-bad-practices-1-lists-as-arrays-9115ba87b0ce
https://medium.com/@adamklein_66511/redux-bad-practices-2-duplicate-code-9f2f3d774d4d
https://medium.com/@adamklein_66511/redux-bad-practices-3-nested-state-6eebf1a410df
https://medium.com/@adamklein_66511/redux-bad-practices-5-duplicate-state-996d259758e3
https://medium.com/@adamklein_66511/redux-bad-practices-6-new-objects-on-the-fly-c38b503948a5
https://medium.com/@adamklein_66511/redux-bad-practices-7-mix-ui-state-with-model-data-cdca6c8d8fd9
Originally published at 500tech.com.