𝗕𝗲𝘄𝗮𝗿𝗲 𝗼𝗳 𝗹𝗼𝗱𝗮𝘀𝗵.𝗺𝗲𝗺𝗼𝗶𝘇𝗲

Lodash memoize looks like free performance. You wrap a function and get a cache.

But the default behavior has a trap. It builds the cache key from the first argument only. It ignores every other argument.

If you use one argument, you are safe. If you use two or more, you create bugs.

Look at this example:

const add = memoize((a, b) => a + b);

add(1, 2); // Returns 3. It caches the result under the key 1. add(1, 9); // Returns 3. This is wrong. It should be 10.

Lodash sees 1 again. It finds 1 in the cache. It returns the old result. It never looks at the 9.

Currency formatting is a common trap.

const formatPrice = memoize((amount, currency) => new Intl.NumberFormat('en', { style: 'currency', currency }).format(amount) );

formatPrice(100, 'USD'); // Returns "$100.00". The key is 100. formatPrice(100, 'EUR'); // Returns "$100.00". This is wrong.

The second call ignores 'EUR'. It sees 100 in the cache and returns dollars instead of euros. There is no error. There is no warning. You just show the wrong money to your users.

You must provide a second argument to define the cache key. This key must cover every input.

const formatPrice = memoize( (amount, currency) => new Intl.NumberFormat('en', { style: 'currency', currency }).format(amount), (amount, currency) => ${amount}|${currency} );

formatPrice(100, 'USD'); // "$100.00" formatPrice(100, 'EUR'); // "€100.00"

The key must capture everything that changes the output.

A final thought: memoization adds risk. Only use it when a function is expensive and runs often with the same inputs. For simple functions, just call them. The risk of a bug is often higher than the speed you gain.

Key takeaways:

Source: https://dev.to/figsify/beware-of-lodashmemoize-it-only-remembers-the-first-argument-4cjl