Pattern Performance Advanced
Memoization
Memoization caches the result of a slow calculation, so a repeat call with the same inputs returns right away instead of recalculating.
The problem
Your component might filter 10,000 products, and every time the parent re-renders for any reason, even if the products array hasn’t changed, the component runs that slow filter again. Typing might start to lag, and scrolling might stutter as users move through the page.
The pattern
Memoization caches the results of slow calculations, so that when the inputs haven’t changed, your code returns the cached value instead of recalculating it.
Problem
I’ve seen performance profiles where a simple sort ran 47 times during a single user interaction because unrelated state changes triggered re-renders, and it produced the same sorted result each time.
Inline callbacks cause a similar problem, because onClick={() => handleClick(id)} creates a new function reference each time the component renders, and any memoized child that receives it re-renders as a result. Your carefully optimized virtualized list might re-render every visible item because of a function that does exactly the same thing as the one before it.
Solution
There are two kinds of cache. A memoized function can keep a result for each set of arguments it has been called with, which suits a function with a few simple arguments. The framework tools only keep the most recent result, and they recalculate it when one of its inputs changes.
In a component, memoization gets used for three separate jobs. The first is caching a calculated value, with useMemo in React, computed in Vue, or $derived in Svelte. The second is keeping a function reference the same between renders, with useCallback. The third is skipping a component’s render when its props haven’t changed, with React.memo. The second and third only help together, because React.memo compares props by reference, so a new inline callback on each render makes the child re-render anyway, and a stable callback does nothing for a child that isn’t memoized. Skipping a render is also only safe for a Pure Component, because memoization is an optimization that depends on the render function being pure.
If your project uses the React Compiler, which has been stable since October 2025, the compiler adds this memoization for you at build time. In most cases, you then only need to write useMemo and useCallback yourself for code that the compiler skips.
I’d avoid memoizing everything. Checking dependencies and managing the cache takes work too, and for a quick operation, that checking can take longer than just recalculating. If you profile first, you’ll know whether you have a real performance problem. That filter on 10,000 products is a good candidate, while adding two numbers together isn’t worth caching.
Example
Memoizing a Function
Fibonacci is the classic example of memoization. Without the cache, each call to fib(n) calculates both of the smaller values from scratch, so the same calls repeat over and over. With the cache, each value from 0 to n is calculated once and then reused.
// Each fib(n) is computed once, then returned from the cache
const fibonacci = (() => {
const cache = {};
return function fib(n) {
if (n in cache) return cache[n];
if (n <= 1) return n;
return cache[n] = fib(n - 1) + fib(n - 2);
};
})();
fibonacci(50); // 12586269025, after about 50 additions instead of the uncached version's 40 billion or so calls
A cache with one entry per argument keeps growing as new arguments come in. If the range of possible inputs has no limit, the cache needs a maximum size, and a Least Recently Used (LRU) cache is the usual choice, because it removes the entries that haven’t been used for the longest time.
Memoizing a Calculated Value
Each version below keeps the last filtered and sorted list, and only recalculates it when products, category, or sortBy changes. The frameworks track those inputs for you. The Vanilla JS version compares the arguments by reference with the ones from the previous call, which is quick even when products is a large array.
function ProductList({ products, category, sortBy }) {
// Only recomputes when products or category change
const filteredProducts = useMemo(() => {
return products.filter(p => p.category === category);
}, [products, category]);
// Chain memoizations for multi-step transformations
const sortedProducts = useMemo(() => {
return [...filteredProducts].sort((a, b) =>
a[sortBy] > b[sortBy] ? 1 : -1
);
}, [filteredProducts, sortBy]);
return (
<ul>
{sortedProducts.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
);
} <script setup>
import { computed } from 'vue';
const props = defineProps(['products', 'category', 'sortBy']);
// computed() automatically memoizes
const filteredProducts = computed(() => {
return props.products.filter(p => p.category === props.category);
});
const sortedProducts = computed(() => {
return [...filteredProducts.value].sort((a, b) =>
a[props.sortBy] > b[props.sortBy] ? 1 : -1
);
});
</script>
<template>
<ul>
<li v-for="product in sortedProducts" :key="product.id">
{{ product.name }}
</li>
</ul>
</template> <script>
let { products, category, sortBy } = $props();
// $derived values are automatically memoized
let filteredProducts = $derived(products.filter(p => p.category === category));
let sortedProducts = $derived([...filteredProducts].sort((a, b) =>
a[sortBy] > b[sortBy] ? 1 : -1
));
</script>
<ul>
{#each sortedProducts as product (product.id)}
<li>{product.name}</li>
{/each}
</ul> // Keeps only the last result, like useMemo
function memoizeLast(fn) {
let lastArgs = null;
let lastResult;
return function(...args) {
const unchanged = lastArgs !== null &&
args.length === lastArgs.length &&
args.every((arg, i) => Object.is(arg, lastArgs[i]));
if (!unchanged) {
lastResult = fn(...args);
lastArgs = args;
}
return lastResult;
};
}
const filterProducts = memoizeLast((products, category) => {
return products.filter(p => p.category === category);
});
filterProducts(products, 'electronics'); // Filters the array
filterProducts(products, 'electronics'); // Same array and category, so returns the last result Callback and Component Memoization
React.memo skips a component’s render when its props are the same references as last time, and useCallback keeps the callback prop the same between renders. Without the useCallback here, TodoItem would get a new onToggle on each render of TodoList, and React.memo would never skip it. Stable Reference covers this in more detail.
function TodoList({ todos, setTodos }) {
// Stable reference prevents child re-renders
const handleToggle = useCallback((id) => {
setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
}, [setTodos]);
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} onToggle={handleToggle} />
))}
</ul>
);
}
// React.memo skips re-render if props unchanged
const TodoItem = React.memo(({ todo, onToggle }) => (
<li onClick={() => onToggle(todo.id)}>{todo.text}</li>
));
React.memo also takes a custom comparison function, for a prop that’s a new object on each render. The comparison has to cover everything the component uses. A shortcut such as comparing data.length would leave stale data on screen whenever items change but the count stays the same.
// options is a new object on each render, so compare the fields the chart uses
const Chart = React.memo(
({ data, options }) => { /* ... */ },
(prev, next) =>
prev.data === next.data &&
prev.options.type === next.options.type &&
prev.options.color === next.options.color
);
Selector Pattern
In Redux, selectors built with reselect return memoized derived state, and they only recalculate it when their inputs change. The Selector page covers them in more detail.
import { createSelector } from 'reselect';
const getProducts = state => state.products;
const getCategory = state => state.category;
// Memoized selector - only recomputes when inputs change
const getFilteredProducts = createSelector(
[getProducts, getCategory],
(products, category) => products.filter(p => p.category === category)
);
// Chained selectors
const getSortedProducts = createSelector(
[getFilteredProducts, state => state.sortBy],
(filtered, sortBy) => [...filtered].sort((a, b) => a[sortBy] > b[sortBy] ? 1 : -1)
);
Benefits
- Slow operations only run when their data changes, so the filter on 10,000 products no longer runs on every render.
- Search boxes and other frequently updated parts of the UI lag less.
- Stable callback references stop a re-render from spreading down through memoized child components.
- You can derive totals and other values from your state without slowing down each render, because they’re only recalculated when their inputs change.
- Mobile devices do less unnecessary CPU work, which helps battery life.
Tradeoffs
- Memoization uses more memory to save CPU time, because each cached value stays in memory until its dependencies change or the component unmounts.
- For quick operations, memoization can make things slower, because comparing dependencies and managing the cache can take longer than just recalculating.
- Dependency arrays in React are easy to get wrong. If you forget a dependency, you get stale cached values, and if you include a reference that changes on each render, the cached value never gets reused.
- Shallow comparison can’t detect nested changes, so if
user.namechanges but theuserobject reference stays the same, the memoized value won’t update. - Debugging memoized code can be confusing, because a breakpoint inside the function only triggers on a cache miss, and a cache hit returns the cached value without running the function body.
- Custom comparison functions in React.memo are easy to get wrong, and if yours is wrong, the component either re-renders too often and wastes work, or re-renders too rarely and shows stale data.
- It’s easy to over-memoize by wrapping everything in useMemo “just in case,” which adds complexity and extra work without making anything faster.
- You should only memoize pure functions, because if a function has side effects, they’ll be skipped on a cache hit or run again when dependencies change unexpectedly, and either one can lead to subtle bugs.
Summary
Memoization caches the results of slow calculations, so a repeat call with the same inputs gets the cached result right away instead of recalculating it. It suits slow operations that are called often with the same arguments. Caching takes work of its own, so if you memoize before you’ve profiled, your code can end up slower and harder to follow.