useCallback and useMemo are both React Hooks that help optimize the performance of a React application by memoizing values. They both accept a func...
For further actions, you may consider blocking this person and/or reporting abuse
In your first example,
handleClickwill get recreated each time you click the button. You may change it to this:Or Simply not use the hook. There's no reason to memoize this kind on function. 😉
Hook useCallback uses useMemo under the hood
Do we have any benchmarks on how much more "optimized" this really is? I can't imagine how much performance is lost between:
and
If it isn't negligible, it has to be pretty close to it. I'd suppose any latency from things like fetching and so on make stuff like this pretty close to irrelevant. Would love to hear anyone's insights or reports from real app world.
I think it's not just the recreation of the function that you would need to take into consideration but the fact that not memoizing functions you pass to other components can cause them to also re-render unnecessarily. If that said component is heavy then it also degrades performance.
Just my two cents ;)
But doesn't React already handle that anyway via props? If you're props to said component (or the component's own state) aren't changing, react isn't going to re-render anything
But if the parent changes without child's props changing?
I think it can help in this case.
@fullstackchris There is a misconception there in what you think isnt changing.
React checks referential integrity to determine if a property has changed/not.
for each render the function's reference will be changed. Therefore, each time the parent re-renders it will pass a new function to the sub component and this component will think the function is new and changed since last render.
When you wrap the function in useCallback then it only changes the reference of the function when the dependencies change
PS:
This is essentially what React does to check equality by default
Very clear explanation of the subtle difference between these two hooks. Nice one!
Thanks Gil :)
Awesome explanation! Thank you!
Great article!
It described the difference clearly, haha
Thank you
Thanks, glad you found this helpful! :)
How did you get the processedData inside useMemo? Perhaps another example would have been better. Because you are returning the memoized function name declaration.
The comment he wrote just above the return statement for processedData states that it's just a placeholder for some code where you would take the inputted data var, do some processing on it, save the results in processedData, and then return that var. It would have been more clear if he gave that var a different name though, for the name to be different than the memoized function name.
Exactly!
Just another GPT article... Horrible...
This comparison is very helpful.
Thank you
Thanks for short and sweet explanation Ahmed, good content.
Thanks Rumen! Glad you found it useful :)