Reputation: 5335
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.
useCallback
for every function passed down to a child? useCallback
because the children will render because the parent rendered anyways? Why isn't this the default behavior? I know that this may not be answerable.
<UpdateGroupInput
onUpdate={useCallback(
group => {
const index = groups.findIndex(searchedGroup => searchedGroup.id === group.id);
const newGroups = groups.slice();
newGroups[index] = group;
onChange(items, newGroups);
hideAddItemModal();
},
[groups, items, onChange]
)}
onDelete={useCallback(
id => {
const newGroups = groups.filter(group => group.id !== id);
const newItems = items.filter(item => item.group !== id);
onChange(newItems, newGroups);
},
[groups, items, onChange]
)}
groups={groups}
visible={viewUpdateGroup}
></UpdateGroupInput>
Upvotes: 6
Views: 3042
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