Diesel
Diesel

Reputation: 5335

Should useCallback always be used when passing a function as a prop?

I have the below code. If I pass the props onUpdate and onDelete as just functions - function objects in javascript - the child components always re-renders due to a props change in the profiler. The function is recreated and onUpdate and onDelete are now new props, makes sense to me.

However, if I add useCallback, they don't perceive a prop change, as this is the purpose of useCallback. So this leads to a few questions.

Upvotes: 6

Views: 3042

Answers (1)

David Bradshaw
David Bradshaw

Reputation: 13077

UseCallback is just a special version of useMemo that is just for use with functions. The advantage is that is stops you recreating the function on each render, which can cause you to break any other memoization further down your component tree.

Like any form of code optimisation the advantages may not be that great, it adds it’s own overhead that may outweigh any advantages and also adds complexity to your code.

To quote Knuth “Premature optimisation is the route of all evil”

Kent C. Dodds has a much more detailed look at this on his blog https://kentcdodds.com/blog/usememo-and-usecallback

Upvotes: 3

Related Questions