Blog>
Snippets

Combining reducers with Object.create(null) initial state

Combine multiple reducers each initialized with state from Object.create(null), for a clean and secure combined state object.
function combineReducers(reducers) {
  return function(state = {}, action) {
    return Object.keys(reducers).reduce((nextState, key) => {
      nextState[key] = reducers[key](state[key], action);
      return nextState;
    }, Object.create(null));
  };
}
Defines a `combineReducers` function that takes an object of reducers and combines them into a single reducer function. The combined reducer updates each slice of state with the corresponding reducer and initializes the state with `Object.create(null)` for a clean prototype-free object.
function todosReducer(state = Object.create(null), action) {
  switch (action.type) {
    case 'ADD_TODO':
      // logic for adding todo
      break;
    // other cases
    default:
      return state;
  }
}
Defines a reducer `todosReducer` which handles actions related to todos. It initializes its state with `Object.create(null)` instead of a regular object literal.
function counterReducer(state = Object.create(null), action) {
  switch (action.type) {
    case 'INCREMENT':
      state.count = (state.count || 0) + 1;
      break;
    case 'DECREMENT':
      state.count = (state.count || 0) - 1;
      break;
    default:
      return state;
  }
  return {...state};
}
Defines a reducer `counterReducer` which handles increment and decrement actions. State is initialized with `Object.create(null)` and ensures immutability by returning a shallow copy of the state.
const rootReducer = combineReducers({
  todos: todosReducer,
  counter: counterReducer
});
Combines the `todosReducer` and `counterReducer` into a single `rootReducer` using `combineReducers`. This will create a state object with the respective slices for todos and counter.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reducer Example</title>
</head>
<body>
<!-- Your HTML Structure -->
<script src="example.js"></script>
</body>
</html>
Basic HTML structure to include the JavaScript code that will use our root reducer.
body {
  /* CSS styles if needed */
}
CSS styles that could be used for styling the HTML elements.