Dependency Array for Computed Values
You'll learn why including all inputs in your useMemo dependency array is critical to avoid getting stale, incorrect cached results.
The Core Problem
When you use useMemo to cache a computed value, React only recalculates that value when something in the dependency array changes. If you forget to include an input that the computation relies on, React will keep returning the old cached result even when that input changes — giving you stale data.
Think of it like a recipe: if your cake depends on flour, eggs, and sugar, but you only tell your assistant to check if flour or eggs changed, they'll serve you yesterday's cake even when you've switched to brown sugar today.
Why Every Input Matters
const [price, setPrice] = useState(100);
const [taxRate, setTaxRate] = useState(0.1);
const [discount, setDiscount] = useState(0);
// ❌ WRONG: discount is missing
const total = useMemo(() => {
return price * (1 + taxRate) - discount;
}, [price, taxRate]);
// If discount changes, total stays stale!
// ✅ CORRECT: all inputs included
const total = useMemo(() => {
return price * (1 + taxRate) - discount;
}, [price, taxRate, discount]);
The first version will keep returning the same total even when discount changes, because React doesn't know to recalculate. The second version correctly includes every value the computation reads.
The Exhaustive-Deps Rule
The ESLint rule exhaustive-deps catches these mistakes automatically. Trust it. If a variable appears inside your useMemo callback, it must be in the dependency array.
Key Takeaway: Your useMemo dependency array must include every value your computation reads — missing dependencies create bugs with stale cached values that are hard to debug.