When using the combination combineReducers
function from Redux, the reducer argument is required and must be a function or an object of functions. The combineReducers
function is responsible for combining multiple reducers into a single reducer function, which can then be used with the Redux store.
Here is an example to illustrate how to use combineReducers
with a single reducer function:
const initialState = {
counter: 0
};
function counterReducer(state = initialState, action) {
switch(action.type) {
case 'INCREMENT':
return {
...state,
counter: state.counter + 1
};
case 'DECREMENT':
return {
...state,
counter: state.counter - 1
};
default:
return state;
}
}
const rootReducer = combineReducers({
counter: counterReducer
});
// Now you can create your Redux store using the rootReducer
const store = createStore(rootReducer);
In the above example, we have a state object with a single property ‘counter’. The counterReducer
function handles all the actions related to the ‘counter’ property. We then use the combineReducers
function to combine the ‘counterReducer’ into a root reducer called ‘rootReducer’.
Note that combineReducers
expects an object of reducers, so the keys in the object correspond to the names of the state properties and the values correspond to the reducer functions that handle those specific properties.
You can add more reducer functions to the object passed to combineReducers
if you have more state properties and action types to handle.