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?
There's no point in using
useCallbackwith a function declared outside of the component. The purpose ofuseCallbackis 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.So if the above examples make sense, you'll notice that
exampleis already stable, so there's no reason to ever useuseCallbackon 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.