Description
Memoization is the act of comparing the inputs to a component, function or variable, and seeing if they were updated. If not, then just return the old value. It's the same idea as a Cache
?
Reach for when
You have an expensive computation that you keep doing.
Don't memoize everything. Memoization has its own cost (comparison + memory).
Pseudocode
| Tool | What | Use When |
|---|---|---|
React.memo(Component) |
Skips re-render if props haven't changed | Expensive presentational components (charts, cards in a list) |
useMemo(() => compute(), [deps]) |
Caches a computed value | Expensive derivations (filtering 10K items, formatting chart data) |
useCallback(fn, [deps]) |
Caches a function reference | Passing callbacks to memoized children (otherwise new reference breaks memo) |
Code
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}