useMemo vs useCallback: The Relationship
What you'll learn: How useMemo and useCallback are fundamentally the same hook with different syntax sugar.
They're Two Sides of the Same Coin
Here's the secret: useCallback is essentially useMemo in disguise. When you write:
const memoizedFunction = useCallback(fn, deps);
React is effectively doing this:
const memoizedFunction = useMemo(() => fn, deps);
The only difference is what you're memoizing: useMemo caches any value (numbers, objects, arrays, or yes—functions), while useCallback is specialized syntax for caching functions specifically.
Why Have Both?
Think of it like having both a Swiss Army knife (useMemo) and a dedicated bottle opener (useCallback). You could open bottles with the knife, but the dedicated tool is clearer and more convenient.
useMemo says: "Remember this computed value"
const expensiveResult = useMemo(() => calculateSomething(a, b), [a, b]);
useCallback says: "Remember this function"
const handleClick = useCallback(() => { doSomething(); }, []);
Both prevent unnecessary recreation on every render. Both use dependency arrays the same way. Both solve the same fundamental problem: keeping references stable.
Choosing Between Them
Use useCallback when you're memoizing a function—it's clearer intent. Use useMemo when you're memoizing the result of calling a function. They're interchangeable for functions, but useCallback is the idiomatic choice.
Key Takeaway: useCallback(fn, deps) is shorthand for useMemo(() => fn, deps). Use useCallback for functions and useMemo for computed values—they're the same mechanism with different ergonomics.