useMemo caches a computed value between renders. useCallback caches a function reference. Both take dependency arrays. Only use them when profiling shows a real performance problem — they add complexity otherwise.
useMemo and useCallback
import { useMemo, useCallback } from "react";
function List({ items, onSelect }) {
// Only recompute when items changes
const sorted = useMemo(
() => [...items].sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
// Stable function reference
const handleClick = useCallback(
(id) => onSelect(id),
[onSelect]
);
return sorted.map(item =>
handleClick(item.id)}>{item.name}
);
}