JavaScriptMedium
What is Memoization?
Memoization is caching a function's results by its arguments, so repeated calls with the same inputs return the stored result instead of recomputing it; it trades memory for speed and only works for pure functions.
How it works
Wrap the function; on each call build a key from the arguments, return the cached value if present, otherwise compute, store and return it.
Choosing the cache key
- Single primitive argument: use it directly as a
Mapkey. - Several primitives: join them or nest Maps.
- Object arguments:
JSON.stringify(slow, order-sensitive) or aWeakMapkeyed by the object (fast, no leaks, but only works if the same object instance is passed again).
When it helps
- Expensive pure computations called repeatedly with the same inputs (formatting, parsing, layout calculations).
- Recursive algorithms with overlapping subproblems (Fibonacci, dynamic programming), where it turns exponential time into linear.
- Caching async results (store the promise, so concurrent callers share one request).
Pitfalls
- Unbounded growth: limit the cache size (LRU) or expire entries.
- Impure functions give stale or wrong results.
- Overhead: for cheap functions, building the key costs more than recomputing.
In React
useMemo (cache a value) and useCallback (cache a function) memoise between renders, and React.memo skips re-rendering a component when props are unchanged. The React Compiler can add much of this automatically.
Code example
js
1function memoize(fn, { maxSize = 100, key = (...args) => JSON.stringify(args) } = {}) {2 const cache = new Map();3 const memoized = (...args) => {4 const k = key(...args);5 if (cache.has(k)) return cache.get(k);6 const value = fn(...args);7 cache.set(k, value);8 if (cache.size > maxSize) cache.delete(cache.keys().next().value); // drop the oldest9 return value;10 };11 memoized.cache = cache;12 return memoized;13}1415let computations = 0;16const slowSquare = (n) => {17 computations++;18 for (let i = 0; i < 1e5; i++); // pretend this is expensive19 return n * n;20};21const fastSquare = memoize(slowSquare);22console.log(fastSquare(12), fastSquare(12), fastSquare(12), "computed", computations, "time"); // 144 144 144 computed 1 time2324// Recursion with overlapping subproblems: exponential -> linear25const countPaths = memoize((rows, cols) =>26 rows === 1 || cols === 1 ? 1 : countPaths(rows - 1, cols) + countPaths(rows, cols - 1)27);28console.log(countPaths(16, 16)); // 155117520 (instant)2930// Async: cache the promise so concurrent calls share one request31let requests = 0;32const getUser = memoize(async (id) => {33 requests++;34 await new Promise((r) => setTimeout(r, 10));35 return { id };36});37await Promise.all([getUser(1), getUser(1), getUser(1)]);38console.log("requests made:", requests); // requests made: 1
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.