As we know that useMemo
is used to memoize a value and useCallback
is used to memoize a function. When it comes to all value except function then I use useMemo
else useCallback
but I wonder what if the value is a function so would memoizing a function using useCallback
and useMemo
are same or not.
function Diff(props) {
const { value } = props;
const memoizedFnUsingMemo = useMemo(() => () => value + value, [value]);
const memoizedFnUsingCallback = useCallback(() => value + value, [value]);
return (
<>
<h1>{memoizedFnUsingMemo()}</h1>
<h1>{memoizedFnUsingCallback()}</h1>
</>
);
}
export default function App() {
const [counter, setCounter] = useState(0);
function changeCounter(change) {
setCounter((c) => c + change);
}
return (
<div>
<h1>counter: {counter}</h1>
<button onClick={() => changeCounter(1)}> increment </button>
<button onClick={() => changeCounter(-1)}> decrement </button>
<Diff value={counter} />
</div>
);
}
The documentation is quite clear about this. Both are equivalent. With
useCallback
you do not have to write an extra wrapper and that just provides more code readability imo.From the docs:
Link