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