Blog>
Snippets

Comparing Objects Created with Object.create(null) in Reducers

Compare previous and current state objects in a reducer that were both initialized using Object.create(null) to detect changes.
function shallowEqual(obj1, obj2) {
  // Check if both arguments are objects and not null
  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false;
  }
  // Compare the sets of keys in both objects
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  // Compare the values associated with each key
  for (let key of keys1) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }
  return true;
}
Defines a shallowEqual function to shallowly compare two objects for equality. Useful for comparing state objects in reducers.
function myReducer(state, action) {
  // Assume a new state object is created in response to an action
  const newState = Object.create(null);
  // ... perform actions on newState ...
  
  // Use shallowEqual to compare old and new state
  if (!shallowEqual(state, newState)) {
    // Return the new state only if it's different from the old state
    return newState;
  }
  // Otherwise, return the old state to avoid unnecessary updates
  return state;
}
An example reducer function that uses the shallowEqual function to compare the previous and current state objects. It only updates the state if there are changes.