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
- How to use ast-grep with GraphQL — posted 2024-09-24
- Next.js App Router (RSC) projects w/ open source code — posted 2024-07-30
- Next.js Relay GraphQL Pokemon example — posted 2024-05-22
- Example Node.js Passport.js SAML app using OneLogin — posted 2024-05-10
- Aphrodite to CSS Modules codemod — posted 2022-12-09
- Simple codemod example with jscodeshift — posted 2021-05-03