Difference between React useCallback with pure function declared inside and outside component

1k views Asked by At

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?

1

There are 1 answers

2
Brian Thompson On

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.