useCallback vs useMemo

· 264 words · 2 minute read

useCallback and useMemo are two of the multiple hooks released with React V16. Hooks are javascript functions which help in isolating some functionality from the functional component (hooks cannot be used inside class based components).

  1. useCallback - As per the official documents, useCallback “Returns a memoized callback”. Here memoized means maintaining or saving a version of the function in the memory for the given array of one or more dependencies.

In the below example you can see that useCallback takes two arguments, first one is the function to be memoized and second one is the array with dependencies. If the dependencies remain same, useCallback returns the existing function from the memory and in case dependency array changes a new is saved in the memory(memoized) and returned.

const memoziedFunction = useCallback(() => {
  // perform some operation with given dependencies
}, [dep1, dep2]);
  1. useMemo - The syntax of useMemo is similar to useCallback but instead of memoizing the function, useMemo stores the return value of the function for the given dependencies. It is specially useful when some expensive computation needs to be done. So if the dependencies remain same during render, the function will return the saved value instead of executing it again.
const memoziedValue = useMemo(() => {
  // perform some operation with given dependencies
  // return value
}, [dep1, dep2]);

Notes:

i) It doesn’t make sense to useCallback or useMemo when either of the dependency changes too frequently. For example, using current time, random number, etc.

ii) If the dependency array is empty, the useCallback and useMemo will run on every single render.