MCPcopy Create free account
hub / github.com/alexreardon/memoize-one

github.com/alexreardon/memoize-one

Chat with this repo
repository ↗ · DeepWiki ↗ · release v7.0.0 ↗ · + Follow · compare 2 versions
38 symbols 98 edges 10 files 0 documented · 0% ● updated 6d agov7.0.0 · 2026-11-23★ 2,969

Browse by type

⨍ Functions 37◇ Types & classes 1
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

memoize-one

A memoization library that only caches the result of the most recent arguments.

npm types Downloads per month

Rationale

Memoization is a technique where a function avoids doing work it has done before by caching results. You are trading memory (cached results) for execution speed (don't need to recompute the result). A memoization cache can quickly use a lot of memory, and so memoization libraries usually to have ways to purge older cache values (eg maxAge, maxSize, exclusions and so on).

memoize-one takes a simpler approach: only remember the latest arguments and their result. If a function is called again with the previous arguments, then return the previously calculated result. This approach ensure there is no need to worry about run away memory costs, and this library can stay extremely small 🙌.

memoize-one covers a surprisingly large amount of real world use cases for memoization - however, there will be cases where a more general purpose memoization library is a better fit (ie when you want a function to cache multiple results and arguments at the same time).

If you have used useMemo and useCallback then you are familiar with how memoize-one works.

Usage

import { memoizeOne } from 'memoize-one';

function add(a, b) {
  return a + b;
}
const memoizedAdd = memoizeOne(add);

memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]

memoizedAdd(1, 2);
// add function: not called
// [cached result is returned: 3]

memoizedAdd(2, 3);
// add function: is called
// [new value returned: 5]

memoizedAdd(2, 3);
// add function: not called
// [cached result is returned: 5]

memoizedAdd(1, 2);
// add function: is called
// [new value returned: 3]
// 👇
// While the result of `add(1, 2)` was previously cached
// `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`)
// so the previous cached result of `(1, 2)` was lost

You can also use the default export:

import memoizeOne from 'memoize-one';

Installation

npm install memoize-one

Supported environments

  • memoize-one@7+ is an ES module only package, written in ES2022 syntax
  • Browsers: browsers that are Baseline widely available (Chrome, Edge and Firefox 111+, Safari 16.4+), with any modern bundler
  • Node.js: import works in all supported versions. require() works in Node.js 20.19+ and 22.12+ (through require(esm))
  • TypeScript projects that compile to CommonJS: use "module": "nodenext" (TypeScript 5.8+) or "module": "node20" (TypeScript 5.9+). With node16 or node18, TypeScript reports error TS1479 for require() of an ES module. You can use a dynamic import() instead
  • Jest: needs extra setup (see upgrading from v6)
// ES modules
import { memoizeOne } from 'memoize-one';

// CommonJS (Node.js 20.19+ and 22.12+)
const { memoizeOne } = require('memoize-one');

If you need to support older environments, please use memoize-one v6.

Function argument equality

By default, we apply our own fast and relatively naive equality function (areInputsEqual) to determine whether the arguments provided to your function are equal. You can see the full code here: memoize-one.ts.

(By default) function arguments are considered equal if:

  1. there is same amount of arguments
  2. each new argument is the same value as the previous argument, according to Object.is

Object.is is the same as strict equality (===), except for two special cases:

  • NaN is equal to NaN
  • +0 and -0 are not equal

This is the same comparison that React uses for hook dependencies (such as in useMemo).

What this looks like in practice:

import { memoizeOne } from 'memoize-one';

// add all numbers provided to the function
const add = (...args = []) =>
  args.reduce((current, value) => {
    return current + value;
  }, 0);
const memoizedAdd = memoizeOne(add);
  1. there is same amount of arguments
memoizedAdd(1, 2);
// the amount of arguments has changed, so add function is called
memoizedAdd(1, 2, 3);
  1. each new argument is the same value as the previous argument, according to Object.is
memoizedAdd(1, 2);
// each argument is the same value as the last argument, so cache is used
memoizedAdd(1, 2);
// second argument has changed, so add function is called again
memoizedAdd(1, 3);
// the first value is not the same value as the previous first value (1 !== 3)
// so add function is called again
memoizedAdd(3, 1);

[special case] NaN is equal to NaN

memoizedAdd(NaN);
// Even though NaN !== NaN, Object.is(NaN, NaN) is true
// so the cache is used
memoizedAdd(NaN);

[special case] +0 and -0 are not equal

memoizedAdd(0);
// Even though 0 === -0, Object.is(0, -0) is false
// so add function is called again
memoizedAdd(-0);

Custom equality function

You can also pass in a custom function for checking the equality of two sets of arguments

const memoized = memoizeOne(fn, isEqual);

An equality function should return true if the arguments are equal. If true is returned then the wrapped function will not be called.

Tip: A custom equality function needs to compare Arrays. The newArgs array will be a new reference every time so a simple newArgs === lastArgs will always return false.

Equality functions are not called if the this context of the function has changed (see below).

Here is an example that uses isEqual from es-toolkit as a deep equal equality check

isEqual from es-toolkit correctly handles deep comparing two arrays

import { memoizeOne } from 'memoize-one';
import { isEqual as isDeepEqual } from 'es-toolkit';

const identity = (x) => x;

const shallowMemoized = memoizeOne(identity);
const deepMemoized = memoizeOne(identity, isDeepEqual);

const result1 = shallowMemoized({ foo: 'bar' });
const result2 = shallowMemoized({ foo: 'bar' });

result1 === result2; // false - different object reference

const result3 = deepMemoized({ foo: 'bar' });
const result4 = deepMemoized({ foo: 'bar' });

result3 === result4; // true - arguments are deep equal

You can build on the default equality check with areInputsEqual. For example, to ignore the last argument:

import { memoizeOne, areInputsEqual } from 'memoize-one';

const memoized = memoizeOne(format, (newArgs, lastArgs) =>
  areInputsEqual(newArgs.slice(0, -1), lastArgs.slice(0, -1)),
);

The equality function needs to conform to the EqualityFn type:

// TFunc is the function being memoized
type EqualityFn<TFunc extends (...args: any[]) => any = (...args: any[]) => any> = (
  newArgs: Parameters<TFunc>,
  lastArgs: Parameters<TFunc>,
) => boolean;

// You can import this type
import type { EqualityFn } from 'memoize-one';

Without a type argument, EqualityFn accepts the arguments of any function. Use it to write one equality function that you can reuse:

import { memoizeOne, areInputsEqual, type EqualityFn } from 'memoize-one';

const ignoreLastArg: EqualityFn = (newArgs, lastArgs) =>
  areInputsEqual(newArgs.slice(0, -1), lastArgs.slice(0, -1));

const memoizedFormat = memoizeOne(format, ignoreLastArg);
const memoizedParse = memoizeOne(parse, ignoreLastArg);

The EqualityFn type allows you to create equality functions that are extremely typesafe. You are welcome to provide your own less type safe equality functions.

Here are some examples of equality functions which are ordered by most type safe, to least type safe:

Example equality function types

// the function we are going to memoize
function add(first: number, second: number): number {
  return first + second;
}

// Some options for our equality function
// ↑ stronger types
// ↓ weaker types

// ✅ exact parameters of `add`
{
  const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ tuple of the correct types
{
  const isEqual = function (first: [number, number], second: [number, number]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ❌ tuple of incorrect types
{
  const isEqual = function (first: [number, string], second: [number, number]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toExtend<EqualityFn<typeof add>>();
}

// ✅ array of the correct types
{
  const isEqual = function (first: number[], second: number[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ❌ array of incorrect types
{
  const isEqual = function (first: string[], second: number[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toExtend<EqualityFn<typeof add>>();
}

// ✅ tuple of 'unknown'
{
  const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ❌ tuple of 'unknown' of incorrect length
{
  const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toExtend<EqualityFn<typeof add>>();
}

// ✅ array of 'unknown'
{
  const isEqual = function (first: unknown[], second: unknown[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ spread of 'unknown'
{
  const isEqual = function (...first: unknown[]) {
    return !!first;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ tuple of 'any'
{
  const isEqual = function (first: [any, any], second: [any, any]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ❌ tuple of 'any' or incorrect size
{
  const isEqual = function (first: [any, any, any], second: [any, any]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().not.toExtend<EqualityFn<typeof add>>();
}

// ✅ array of 'any'
{
  const isEqual = function (first: any[], second: any[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ two arguments of type any
{
  const isEqual = function (first: any, second: any) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ a single argument of type any
{
  const isEqual = function (first: any) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

// ✅ spread of any type
{
  const isEqual = function (...first: any[]) {
    return true;
  };
  expectTypeOf<typeof isEqual>().toExtend<EqualityFn<typeof add>>();
}

this

memoize-one correctly respects this control

This library takes special care to maintain, and allow control over the the this context for both the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's this context respect all the this controlling techniques:

  • new bindings (new)
  • explicit binding (call, apply, bind);
  • implicit binding (call site: obj.foo());
  • default binding (window or undefined in strict mode);
  • fat arrow binding (binding to lexical this)
  • ignored this (pass null as this to explicit binding)

Changes to this is considered an argument change

Changes to the running context (this) of a function can result in the function returning a different value even though its arguments have stayed the same:

function getA() {
  return this.a;
}

const temp1 = {
  a: 20,
};
const temp2 = {
  a: 30,
};

getA.call(temp1); // 20
getA.call(temp2); // 30

Therefore, in order to prevent against unexpected results, memoize-one takes into account the current execution context (this) of the memoized function. If this is different to the previous invocation (according to Object.is) then it is considered a change in argument. further discussion.

Generally this will be of no impact if you are not explicity controlling the this context of functions you want to memoize with explicit binding or implicit binding. memoize-One will detect when you are manipulating this and will then consider the this context as an argument. If this changes, it will re-execute the original function even if the arguments have not changed.

Clearing the memoization cache

A .clear() property is added to memoized functions to allow you to clear it's memoization cache.

This is helpful if you want to:

  • Release memory
  • Allow the result function to be called again without having to change arguments

```ts import { memoizeOne } from 'memoize-one';

function add(a: number, b: number): nu

Extension points exported contracts — how you extend this code

browse all types & interfaces →

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 37
Interface 1

Languages

TypeScript100%

Modules by API surface

test/types-test.spec.ts11 symbols
test/memoize-one.spec.ts10 symbols
benchmarks/comparison/v6.ts4 symbols
benchmarks/comparison/run.ts4 symbols
src/memoize-one.ts3 symbols
benchmarks/comparison/scenarios.ts3 symbols
benchmarks/library-comparison/index.js2 symbols
benchmarks/comparison/worker.ts1 symbols

Dependencies from manifests, versioned

@arethetypeswrong/cli0.18.5 · 1×
@size-limit/preset-small-lib14.3.0 · 1×
@types/node22.20.5 · 1×
es-toolkit1.53.2 · 1×
fast-memoize2.5.2 · 1×
lodash-es4.18.1 · 1×
markdown-table3.1.0 · 1×
memoize11.0.0 · 1×
memoize-onefile:../.. · 1×
memoizee0.4.17 · 1×
micro-memoize5.2.2 · 1×
oxlint1.93.0 · 1×

For agents

$ claude mcp add memoize-one \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page