Reputation: 5234
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:
const someFunc = () => {
let someVar = "someVal";
return someVar;
};
const someFuncCallback = React.useCallback(someFunc , [])
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).
returning the cached result when the same inputs occur again
, so maybe I don't get somethings, which of them is correct?
Upvotes: 14
Views: 14753
Reputation: 281656
Everytime your component re-render, a new instance of the function is created, useCallback is just an addition which assigns the reference to another variable.
The original function is recreated regardless of whether you use useCallback or not.
Also with the usage of useCallback
react actually memoizes the function passed as argument to it, and returns the same reference of the function on next re-render if the dependency didn't change.
Also note that if you use a useCallback
function it optimizes re-renders for the child components too if you pass the function as prop to child component.
So using a useCallback hook is optimal when you pass on the function to child components or use it as dependency to useEffect or other functions called with useCallback
Check the docs for more details.
Returns a memoized callback.
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g.
shouldComponentUpdate
).
useCallback(fn, deps)
is equivalent touseMemo(() => fn, deps)
.
Upvotes: 13