Does useCallback have a semantic guarantee?

Viewed 438

The React documentation says the following about useMemo

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

For useCallback there is the following line:

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

The word "equivalent" is a bit fuzzy for me and I don't know if that also means that useCallback does not provide a semantic guarantee.

1 Answers

useMemo is equal to useCallback if the return value of the useMemo was a function:

// The return value of `useMemo` is calculated every time deps change
useMemo(() => {
  return () => { // do some stuff }
}, [deps])

// The function block within `useCallback` is redefined every time deps change
useCallback(() => {
  // do some stuff
}, [deps])

I don't know the reason why they made separate hooks for this but I guess they are technically doing the same thing.

As for having a semantic guarantee, I'd say they might do the same thing with useCallback to "free some memory" but a function memory consumption is less significant than actual data.

Related