Reputation: 3405
At react docs I've read
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).
That's fine, we need to prevent unnecessary renders for the childs, but for the current component that is using the useCallback
, what useCallback
really offer?
As far as I know useCallback
is about preventing the current component re-renders from creating the same function over and over again(correct me if I'm wrong) and it will keep a reference to the same function (without creating a new one) as far as the dependency array include the same references.
Is it right? Or we have something deeper?
I've checked this great answer but it's talking about preventing (childs) re-renders, I'm looking for what useCallback
means for the current component.
Upvotes: 2
Views: 108
Reputation: 82219
useCallback
does not improve performance of the component it is defined in (in fact it makes it very slightly worse, as there's a bit more work for React to do on each render). It'll make no difference at all to the frequency that component re-renders.
On each render of your component, JS is still 'creating' a new function each time. The useCallback will simply throw this new function away if the dependencies haven't changed, and return the previous one.
useCallback
is useful in two cases:
You pass the callback to a component that uses React.memo
(to ensure it only re-renders if props change). Without useCallback that child component would re-render every time the parent renders.
You (or a child component, or a custom hook) wishes to use the callback in a useEffect
and you want to reduce the number of times the effect runs.
Upvotes: 5