React Hooks In DepthLesson 3.4
useMemo and useCallback: when and how to use memoization
useMemo syntax, useCallback syntax, referential equality, memoization cost, when NOT to memoize, dependency arrays, preventing unnecessary child re-renders
Memoization in React
Memoization caches a result and reuses it if inputs haven't changed. React provides two hooks for this: useMemo for values and useCallback for functions.
useMemo
import { useMemo, useState } from 'react';
function ProductList({ products, filterText }) {
// Only recalculates when products or filterText changes
const filtered = useMemo(
() => products.filter(p => p.name.includes(filterText)),
[products, filterText]
);
return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}useCallback
import { useCallback, useState } from 'react';
function Parent() {
const [count, setCount] = useState(0);
// Stable function reference across renders
const handleDelete = useCallback((id) => {
console.log('Delete', id);
}, []); // no dependencies โ function never changes
return <Child onDelete={handleDelete} />;
}Both hooks are optimization tools โ not default practice. Every memoization has a cost: memory and comparison overhead. Apply them only when profiling shows a real performance problem or when passing callbacks to memoized child components. Premature memoization adds complexity without benefit.
