DEV Community

Rafi
Rafi

Posted on

Memoization of Immutable.js using hash code

Immutable.js returns new reference after each operation on its collection. When you have Redux state that is immutable this might be a problem and it might cause unwanted re-renders. All Immutable.js collections have a function called hashCode() that returns same string as long as the collection contain the same elements in same order. You can use that to create a memoization function as follows.

const memoizeByHashCode = () => {
  let oldValue = {};
  return (value: Object) => {
    if (Object.keys(oldValue).length === 0) {
      oldValue = value;
      return value;
    } else if (value.hashCode() === oldValue.hashCode()) {
      return oldValue;
    } else {
      oldValue = value;
      return value;
    }
  };
};

Now you can use this function to return same reference if value did not change

const remember = memoizeByHashCode();
const collection1 = remember(add(1));
const collection2 = remember(add(1));

Now collection1 and collection2 will point to the same reference.

This post is actually cross published from https://rafi993.me/posts/2019-15-10--Memoization-of-Immutable.js-using-hash-code/

Top comments (0)