React's useCallback
hook offers a performance gain when passing the generated (memoized) function to a child component in order to avoid unnecessary re-renders.
Do I get any performance gain when the hook is used as internal ("private") function? For example:
function Foo({numbers}) {
const dep1 = React.useMemo(() => {......}, [....])
const calc = React.useCallback((a) => a * dep1, [dep1])
return (
<>
{numbers.map((num) => (
<div key={num}>
Num: {num}, Calculated: {calc(num)}
</div>
))}
</>
);
}
or does a simple
const calc = (a) => a * dep1
is the same for that case?
In other words, since useCallback
is memoizing the function reference, not the function itself, do I have to use it when not passing it as a prop?
For local usage (inside of the component) useCallback
literally doesn't make any improvements. It will be called on each re-render and even taking the fact it will take an original function object from memory, it still will re-create the inline function.
However, useMemo
can make sense if it caches a value received from some heavy calculations. It use the memoization principle which is useful for avoiding redundant heavy operations.
P.S.
It worth noting that the only justified use case of wrapping private method with useCallback
is if (for any reason) you are going to put this method into useEffect dependencies.