2

I am trying to understand the difference between useMemo and useCallback and this statement in the documentation "useCallback(fn, deps) is equivalent to useMemo(() => fn, deps)."

So in useMemo, I have to pass a function that returns a function? In useCallback, I simply return a function. I get useCallback, but I am not sure about useMemo and this function that returns a function (or do I have this all wrong). Reading the SO posts is not helping here quite yet.

If useMemo is calling a function that returns a function, when is the second function called in react?

Dean Hiller
  • 19,235
  • 25
  • 129
  • 212

2 Answers2

3

If you want to memoize a function you will use useCallback, syntax: useCallback(fn, deps). But if you want to memoize the return value of the function then you should use useMemo, syntax: useMemo(() => fn(), deps)

Now If I compare two syntaxes in the following statement

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps)

Here for useMemo you're not invoking fn so you get that function itself not the return value of it. In this case both useCallback(fn, deps) and useMemo(() => fn, deps) give you the memoized fn.

0

useMemo

Return a memorized value. Means it gives you referential equity for value.

useCallback

Return a memorized callback. Means it gives you referential equity for functions.

yash sanghavi
  • 368
  • 3
  • 5