DEV Community

Randy Rivera
Randy Rivera

Posted on

Redux: Combine Multiple Reducers

  • Remember the first principle of Redux: all app state is held in a single state object in the store. You define multiple reducers to handle different pieces of your application's state, then compose these reducers together into one root reducer.
  • The root reducer is then passed into the Redux createStore() method.
  • Redux gives us the combineReducers() method. Which accepts an object as an argument in which you define properties and give them keys to specific reducer functions.
  • For the example coming up the state held in the Redux store would be a single object containing count and auth properties.
  • Code:
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

const counterReducer = (state = 0, action) => {
  switch(action.type) {
    case INCREMENT:
      return state + 1;
    case DECREMENT:
      return state - 1;
    default:
      return state;
  }
};

const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';

const authReducer = (state = {authenticated: false}, action) => {
  switch(action.type) {
    case LOGIN:
      return {
        authenticated: true
      }
    case LOGOUT:
      return {
        authenticated: false
      }
    default:
      return state;
  }
};

const rootReducer = // Define the root reducer here

const store = Redux.createStore(rootReducer);
Enter fullscreen mode Exit fullscreen mode
  • With the counterReducer() and authReducer() functions provided to us along with the Redux store. Let's finish writing the rootReducer() function using the Redux.combineReducers() method. Then we have to give counterReducer and authReducer a key.
  • Answer:
const rootReducer = Redux.combineReducers({
  count: counterReducer,
  auth: authReducer
}) 

const store = Redux.createStore(rootReducer);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)