Search code examples
javascriptmemoizationimmer.js

Use memoized value in immer.js draft


I have a complex object (graph - nodes and edges) in state which I update with immer.js. I memoize some computations on the object (e.g. node adjacency list) using memoize-one library. However this is a problem since the draft is not identical with the original object.

Is there a way to solve this, e.g. somehow extract original object from immer.js draft?

Note that I use a curried producer, therefore producer declaration has no access to the original object.

Simple example of the issue:

const x = { foo: { bar: "bar" } };

const barLength = memoizeOne(foo => {
  console.log("updating memoized value...");
  return foo.bar.length;
});

console.log("value updated", barLength(x.foo));
console.log("memoized value used", barLength(x.foo));

const producer = produce(draft => {
  draft.lastFooBarLength = barLength(draft.foo); // triggers update memoized value
});

console.log(producer(x).lastFooBarLength);

Solution

  • There is a function which is called literally original that does that:

    https://immerjs.github.io/immer/docs/original