Both cache something across renders so it isn't recomputed/recreated every time:
useMemocaches a .
Both cache something across renders so it isn't recomputed/recreated every time:
useMemo caches a .useCallback caches a function's identity (it's useMemo(() => fn, deps)).They exist to avoid (a) repeating expensive work and (b) breaking referential equality that memoized children rely on.
function Table({ rows, onSelect }) {
// (a) expensive computation — recompute only when `rows` changes
const sorted = useMemo(() => rows.slice().sort(byName), [rows]);
// (b) stable function identity — so a React.memo child doesn't re-render,
// and effects depending on it don't re-fire
const handleSelect = useCallback(id => onSelect(id), [onSelect]);
return <Grid rows={sorted} onSelect={handleSelect} />;
}
Bedħala useCallback, handleSelect hija funzjoni ġdida kompletament kull render. A React.memo(Grid) kont tara prop "ġdid" u kont terenderizza anyway, li jiddefeat il-memoization. L-istess għal object li jitpassja lil memoized child jew użat f'useEffect dependency array.
const x = useMemo(() => a + b, [a, b]); // ❌ pointless — adding is cheaper than memoizing
useMemo/useCallback kullimkien iżid noise u jista' jkun anqas mabda'. (React 19's compiler jista' auto-memoize, jitqajjal il-ħtieġa.)