0

Will there be a difference between these two approaches?:

// outside component
const magicIdx = (i) => (i - 1) / 3

//inside component
const calcIdxOut = useCallback(magicIdx, [])
const calcIdxIn = useCallback((i) => (i - 1) / 3, [])

Does defining a pure function outside the component and using it in a useCallback without dependencies makes any difference?

Lucas Steffen
  • 1,244
  • 2
  • 10
  • 22

1 Answers1

1

There's no point in using useCallback with a function declared outside of the component. The purpose of useCallback is to give referential stability to a function, even though that function is technically redefined every render. Since that only applies to functions defined inside the component, it does nothing useful here.

// Stable reference - only declared once
function example() {}

function App() {
  // Unstable reference - redeclared each time App renders
  function example2() {}

  // Stable reference - even though example2 changes, 
  // example3 reference only changes if dependencies to useCallback change.
  const example3 = useCallback(example2, []);
}

So if the above examples make sense, you'll notice that example is already stable, so there's no reason to ever use useCallback on it.

Your function is not expensive, so unless the purpose here is to prevent a memoized child component from re-rendering, referential stability really isn't a large concern anyway.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • That's not strictly true. A function can be defined outside the component using `useCallback`, but still being recreated on every render in a parent component. I think it's important to discriminate this. If a function is created _outside all components which are parent components or aren't being memoized with the same dependencies_, then `useCallback` is not necessary. Otherwise, it is still potentially a useful optimization: it depends on exactly where the callback function in question is being instantiated. – jsejcksn May 02 '22 at 15:07
  • I feel like saying outside the component, along with the example showing it, implies that we are talking about outside *all* components. `useCallback` is rarely used effectively anyway, since most people don't understand that the child component needed to be memoized for it to be helpful. – Brian Thompson May 02 '22 at 15:53