Blog>
Snippets

Modular Reducer Composition

Create separate reducer functions for different entities and demonstrate how to combine them with combineReducers for a scalable state management solution.
import { combineReducers } from 'redux';

// User reducer managing state for users
function userReducer(state = [], action) {
  switch (action.type) {
    case 'ADD_USER':
      return [...state, action.payload];
    case 'REMOVE_USER':
      return state.filter(user => user.id !== action.payload.id);
    // Add more user related cases as needed
    default:
      return state;
  }
}

// Post reducer managing state for posts
function postReducer(state = [], action) {
  switch (action.type) {
    case 'ADD_POST':
      return [...state, action.payload];
    case 'REMOVE_POST':
      return state.filter(post => post.id !== action.payload.id);
    // Add more post related cases as needed
    default:
      return state;
  }
}

// Combine the reducers to create a root reducer
const rootReducer = combineReducers({
  user: userReducer,
  post: postReducer
});

export default rootReducer;
This code defines two individual reducer functions for users and posts, each responsible for handling actions for their respective parts of the state. The userReducer handles 'ADD_USER' and 'REMOVE_USER' actions, while the postReducer handles 'ADD_POST' and 'REMOVE_POST' actions. Finally, the combineReducers helper from Redux combines these reducers into a single rootReducer, which then can be used in the Redux store.