What is the difference between useMemo and useCallback in case of memoizing a function

67 views Asked by At

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.

CODESANDBOX

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>
  );
}
1

There are 1 answers

0
Tushar Shahi On BEST ANSWER

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:

Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into useCallback instead of useMemo to avoid having to write an extra nested function. The two examples above are completely equivalent. The only benefit to useCallback is that it lets you avoid writing an extra nested function inside. It doesn’t do anything else.

Link