Combining Reducers
In larger Redux applications, it's common to have multiple reducers that manage different parts of the application state. For example, you might have a separate reducer for managing the state of a movie collection and another reducer for managing the state of a user profile.
To combine these reducers, Redux provides the combineReducers function. This function creates a higher-order reducer that internally calls the individual reducers and combines their state into a single state object.
Here's an example of how to use combineReducers to combine the movieReducer and userReducer:
JAVASCRIPT
1const movieReducer = (state = [], action) => {
2 // handle movie-related actions
3};
4
5const userReducer = (state = {}, action) => {
6 // handle user-related actions
7};
8
9import { combineReducers } from 'redux';
10
11const rootReducer = combineReducers({
12 movies: movieReducer,
13 user: userReducer
14});xxxxxxxxxx37
// Output: {}// Let's say we have two separate reducers for managing the state of a movie collection and a user profileconst movieReducer = (state = [], action) => { // handle movie-related actions};const userReducer = (state = {}, action) => { // handle user-related actions};// To combine these two reducers, we can use the `combineReducers` function provided by Reduximport { combineReducers } from 'redux';const rootReducer = combineReducers({ movies: movieReducer, user: userReducer});// The `combineReducers` function creates a higher-order reducer that internally calls `movieReducer` and `userReducer`// The created rootReducer can now be used to create the Redux storeimport { createStore } from 'redux';const store = createStore(rootReducer);console.log(store.getState());// Output: { movies: [], user: {} }OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


