README
memoize-one
A memoization library that only caches the result of the most recent arguments.
Rationale
Cache invalidation is hard:
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
So keep things simple and just use a cache size of one!
Unlike other memoization libraries, memoize-one
only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as maxAge
, maxSize
, exclusions
and so on which can be prone to memory leaks. memoize-one
simply remembers the last arguments, and if the function is next called with the same arguments then it returns the previous result.
Usage
Standard usage
import memoizeOne from 'memoize-one';
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);
memoizedAdd(1, 2); // 3
memoizedAdd(1, 2); // 3
// Add function is not executed: previous result is returned
memoizedAdd(2, 3); // 5
// Add function is called to get new value
memoizedAdd(2, 3); // 5
// Add function is not executed: previous result is returned
memoizedAdd(1, 2); // 3
// Add function is called to get new value.
// While this was previously cached,
// it is not the latest so the cached result is lost
Custom equality function
You can also pass in a custom function for checking the equality of two items.
import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';
const identity = x => x;
const defaultMemoization = memoizeOne(identity);
const customMemoization = memoizeOne(identity, deepEqual);
const result1 = defaultMemoization({foo: 'bar'});
const result2 = defaultMemoization({foo: 'bar'});
result1 === result2 // false - difference reference
const result3 = customMemoization({foo: 'bar'});
const result4 = customMemoization({foo: 'bar'});
result3 === result4 // true - arguments are deep equal
Equality function type signature
Here is the expected flow type signature for a custom equality function:
type EqualityFn = (a: mixed, b: mixed) => boolean;
Custom equality function with multiple arguments
If the function you want to memoize takes multiple arguments, your custom equality function will be called once for each argument and will be passed each argument's new value and last value.
import memoizeOne from 'memoize-one';
const makeCountObj = (first, second, third) => ({
first: first.count,
second: second.count,
third: third.count,
});
const areCountPropertiesEqual = (newArg, lastArg) => newArg.count === lastArg.count;
// runs once for first's new and last values, once for second's, etc.
const memoizedMakeCountObj = memoizeOne(makeCountObj, areCountPropertiesEqual);
const result1 = memoizedMakeCountObj(
{a: '?', count: 1},
{a: '