Blog>
Snippets

Advanced Redux: Splitting and Combining Reducers

Show how to split a complex reducer into smaller functions and combine them using combineReducers in Redux Toolkit.
import { createStore, combineReducers } from 'redux';

// Example individual reducers
function userReducer(state = {}, action) {
  switch (action.type) {
    case 'UPDATE_USER':
      return { ...state, ...action.payload };
    default:
      return state;
  }
}

function postsReducer(state = [], action) {
  switch (action.type) {
    case 'ADD_POST':
      return [...state, action.payload];
    default:
      return state;
  }
}

// Combine reducers
const rootReducer = combineReducers({
  user: userReducer,
  posts: postsReducer
});

// Store creation
const store = createStore(rootReducer);

export default store;
In this JavaScript code, individual `userReducer` and `postsReducer` manage different slices of the application's state. The `combineReducers` function from Redux is used to create a single root reducer that manages the overall state shape. It's then used to create the Redux store which holds the state of the application.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Redux Example</title>
<script src='path-to-redux.js'></script>
<script src='path-to-your-store.js' defer></script>
</head>
<body>
  <!-- Your HTML components here -->
</body>
</html>
This HTML template includes Redux and the store module. Replace 'path-to-redux.js' with the actual path to your Redux library and 'path-to-your-store.js' with the path to your JavaScript file where you configured your Redux store.
body {
  font-family: Arial, sans-serif;
}

/* Additional CSS can go here for styling your application */
This CSS snippet sets a default font for the body of the page. More styles can be added to adjust the appearance of HTML components related to Redux.