I'm optimizing performance to an app and I wondered if to use useCallback hook on function that those not depend on any variable.
consider the following case: let's say we have some function:
const someFunc = () => {
let someVar = "someVal";
/**
* here some extra calculations and statements regarding 'someVar'.
* none of the statements depends on a variable outside this function scope.
*/
return someVar;
};
This function does not depend on any variable so we can wrap it with useCallback with an empty array:
const someFunc = useCallback(() => {
let someVar = "someVal";
return someVar;
}, []);
now my question is - Does:
- react actually declare the function (with memory allocation and things, something like this):
const someFunc = () => {
let someVar = "someVal";
return someVar;
};
const someFuncCallback = React.useCallback(someFunc , [])
- OR react does first check the dependencies array, and if none of the dependencies changed used to previously allocated function in the memory?
if the first statement is true, then we should not use useCallback on functions that do not depend on any other var because the function will be declared all over again anyway.
but if the second statement is true then we should use useCallback hook on any function that is more 'expensive' to declare then a single useCallback call statement, but I have no idea how expensive it to call to react useCallback (from the perspective of memory and CPU usages).
I found this very nice blog which says that the first statement is true. but if you check react docs about useCallback hook you will see it written that react useCallback uses memorized call which means
returning the cached result when the same inputs occur again, so maybe I don't get somethings, which of them is correct?
useCallbackwill discard it and return the old function if the dependencies didn't change. This makes a difference in performance when you're passing this function further down to a memoized component.