Search code examples
javascriptreactjswebpackmemoization

Import and use nano-memoize in react application?


I am trying to use Nano-memoize in my React based web application which also uses Typescript and Webpack.

I have followed the following steps:

  • npm install nano-memoize
  • added import * as nanomemoize from 'nano-memoize' to my source file.
  • memoized a function like const memoizedFunc = nanomemoize(myFunc)

myFunc takes two arguments - a string and an string[].

However, I don't see the memoization happening because the debug statements in myFunc are getting printed for same arguments.
How should this be done the right way?


Solution

  • Nano-memoize doesn't do deep equals comparison of arguments. The string[] arguments passed in to myFunct is different object each time and consequently memoization doesn't work.

    To fix this I am forced to use lodast.isquals as an option in nano-memoize

    const memoizedFunc = nanomemoize(myFunc, {
        // deep equals required since one of the parameter is a string array
        equals : (x, y) => isequal(x, y),
    });