What does Redux's combineReducers do?
Redux uses a single root reducer function that accepts the current state (and an action) as input and returns a new state. Users of Redux may write the root reducer function in many different ways, but a recommended common practice is breaking up the state object into slices and using a separate sub reducer to operate on each slice of the state. Usually, Redux's helper utility, combineReducers
is used to do this. combineReducers
is a nice shortcut because it encourages the good practice of reducer composition, but the abstraction can prevent understanding the simplicity of Redux reducers.
The example below shows how a root reducer could be written without combineReducers
:
Given a couple of reducers:
function apples(state, action) {
// do stuff
return state;
};
function bananas(state, action) {
// do stuff
return state;
};
This reducer created with combineReducers
:
const rootReducer = combineReducers({ apples, bananas });
is equivalent to this reducer:
function rootReducer(state = {}, action) {
return {
apples: apples(state.apples, action),
bananas: bananas(state.bananas, action),
};
};
Usage without ES6 concise properties¶
The above example used ES6 concise properties, but combineReducers
can also be used without concise properties. This reducer created with combineReducers
:
const rootReducer = combineReducers({
a: apples,
b: bananas
});
is equivalent to this reducer:
function rootReducer(state = {}, action) {
return {
a: apples(state.a, action),
b: bananas(state.b, action),
};
};
Understanding how combineReducers
works can be helpful in learning other ways reducers can be used.
References / see also ¶
Related posts
- Aphrodite to CSS Modules codemod — posted 2022-12-09
- Simple codemod example with jscodeshift — posted 2021-05-03
- Buildtime vs runtime environment variables with Next.js and Docker — posted 2021-04-13
- Next.js GitLab CI/CD Docker multi-stage example — posted 2021-04-06
- Next.js Cypress GitLab CI example — posted 2021-03-25
- Example Next.js GitLab CI/CD Amazon ECR and ECS deploy pipeline — posted 2021-03-25