DEV Community

Rafi
Rafi

Posted on

3

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/

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more