Both useCallback and useMemo are React Hooks used to optimize performance by memoizing values or functions, but they serve slightly different purposes.
1️⃣ useCallback
- Memoizes a function
- Returns a cached version of the function that only changes if its dependencies change
- Useful to prevent unnecessary re-renders when passing callbacks to child components
import React, { useState, useCallback } from "react";
function Parent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []); // function is recreated only if dependencies change
return <Child onClick={increment} />;
}
function Child({ onClick }) {
console.log("Child rendered");
return <button onClick={onClick}>Increment</button>;
}
✅ Prevents Child from re-rendering unnecessarily if onClick stays the same.
2️⃣ useMemo
- Memoizes a value (result of a computation)
- Returns a cached value that is recalculated only when dependencies change
- Useful for expensive calculations
import React, { useState, useMemo } from "react";
function Component() {
const [count, setCount] = useState(0);
const expensiveValue = useMemo(() => {
console.log("Calculating...");
return count * 2;
}, [count]); // recalculated only when count changes
return (
<div>
<p>{expensiveValue}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
✅ Prevents recalculating heavy computations on every render.
3️⃣ Key Differences
| Feature | useCallback |
useMemo |
|---|---|---|
| Memoizes | Function | Value / Computation result |
| Returns | Function | Result of function |
| Use case | Passing stable callbacks to children | Expensive calculations |
| Example | onClick={useCallback(...)} |
const value = useMemo(...) |
⚡ In short:
useCallback→ caches a function to avoid recreating it unnecessarily.useMemo→ caches a value from an expensive computation to avoid recalculating on every render.
They both rely on dependency arrays to decide when to update.