Interview frequency: …
Short answer
useMemo caches the result of an expensive calculation, while useCallback preserves the identity of a function passed between renders to avoid rendering children optimized with React.memo; using them for simple work adds unnecessary memory and comparison costs.
Explanation
useMemo runs a function and stores its result, recalculating only when dependencies change. useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Using these Hooks for simple calculations (such as adding two numbers) uses extra memory and compares dependencies on every render without a real benefit.
Code example
// useMemo For an expensive filtering operation
const filteredList = useMemo(() => {
return hugeList.filter(item => item.score > threshold);
}, [hugeList, threshold]);
// useCallback To stabilize the function reference passed to a component wrapped in React.memo
const handleSelect = useCallback((id: string) => {
setSelectedId(id);
}, []);Common mistakes
- Wrapping every function in the application with useCallback even when it is not passed to a memoized component or used as another Hook's dependency.