Lesson 4 of 11
useMemo & useCallback - Memoization
useMemo caches a computed value; useCallback caches a function reference. Both exist to solve the same underlying problem: on every render, new object/function references are created, which can break memoized children or trigger unnecessary effects. The key skill is knowing WHEN they actually help - not applying them everywhere.
useMemo - Caching Expensive Computations
import { useMemo, useState } from 'react';
// Without useMemo: runs every render regardless
function ProductList({ products, filterText }: { products: Product[]; filterText: string }) {
// If products has 10,000 items, this runs on EVERY render - even unrelated ones
const filtered = products.filter(p =>
p.name.toLowerCase().includes(filterText.toLowerCase())
);
return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// With useMemo: runs only when products or filterText changes
function ProductList({ products, filterText }: { products: Product[]; filterText: string }) {
const filtered = useMemo(
() => products.filter(p =>
p.name.toLowerCase().includes(filterText.toLowerCase())
),
[products, filterText] // only recompute when these change
);
return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
// Referential stability - useMemo for stable object references
function Dashboard({ userId }: { userId: string }) {
// Without useMemo: new object every render โ child sees new prop โ re-renders
const config = { userId, theme: 'dark' }; // โ new reference every render
// With useMemo: same reference unless userId changes
const config = useMemo(
() => ({ userId, theme: 'dark' }),
[userId]
); // โ
stable reference
return <MemoizedChart config={config} />;
}
// When NOT to use useMemo:
// โ Don't use it for simple/fast computations - overhead of memoization > computation cost
const total = price * quantity; // โ NO need for useMemo
const greeting = `Hello, ${name}`; // โ NO need for useMemouseCallback - Stable Function References
import { useCallback, memo, useState } from 'react';
// useCallback = useMemo applied to a function
// useCallback(fn, deps) โก useMemo(() => fn, deps)
// Without useCallback: new function reference every render
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => console.log('clicked'); // โ new function every render
// If Child is memo'd, it will STILL re-render because handleClick is new
return (
<>
<button onClick={() => setCount(c => c + 1)}>Inc</button>
<MemoizedChild onClick={handleClick} />
</>
);
}
// With useCallback: stable reference - Child stays memoized
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('clicked');
}, []); // stable - never changes
// If you need to use state inside, include it in deps:
const handleDelete = useCallback((id: string) => {
setItems(prev => prev.filter(item => item.id !== id));
}, []); // setItems is stable (from useState) - safe to omit
return (
<>
<button onClick={() => setCount(c => c + 1)}>Inc ({count})</button>
<MemoizedChild onClick={handleClick} />
</>
);
}
// React.memo - memoize a child component
const MemoizedChild = memo(function Child({ onClick }: { onClick: () => void }) {
console.log('Child rendered'); // only logs when onClick reference changes
return <button onClick={onClick}>Click me</button>;
});Common Mistakes - useMemo & useCallback
- Wrapping EVERYTHING in useMemo/useCallback - premature optimization; each memoization has a cost (memory, comparison work); only apply when you've measured a problem
- Missing dependencies causing stale closures - if a value used inside useMemo/useCallback isn't in the deps array, the cached version captures a stale copy
- Using memo without useCallback - `React.memo` on a child is useless if the parent passes a new inline function every render; pair them together
- Using useMemo to prevent side effects - useMemo can run multiple times in React 18 Strict Mode; never put side effects inside it (fetch calls, DOM mutations, etc.)
- Not measuring before optimizing - React DevTools Profiler shows you exactly which renders are slow; fix only after profiling reveals a real problem, not hypothetically
Tip
Tip
Practice useMemo useCallback Memoization in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for useMemo & useCallback - Memoization
Practice Task
Note
Practice Task - (1) Write a working example of useMemo useCallback Memoization from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with useMemo useCallback Memoization is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- useMemo caches a computed value; useCallback caches a function reference.
- Wrapping EVERYTHING in useMemo/useCallback - premature optimization; each memoization has a cost (memory, comparison work); only apply when you've measured a problem
- Missing dependencies causing stale closures - if a value used inside useMemo/useCallback isn't in the deps array, the cached version captures a stale copy
- Using memo without useCallback - `React.memo` on a child is useless if the parent passes a new inline function every render; pair them together
Finished this lesson?