My 2 cents on useCallback React hook.
useCallback hook memoizes the callback function passed to it as argument. In simple words it will not create another instance of same function until the value in second argument passed in the useCallback as array of dependency changes.
Simple way to test whether the passed callback function has changed is by the set
test. When ever the useCallback hook is called, add the function returned to the set and check the size of the set. if the size has increased that means a new function instance has been created.
When you call useCallback hook with only one argument, that is without dependencies it does nothing.
I think i have got the basics right. But i am not able to solve un necessary re-rendering of <ShowProducts/>
component.
First of all why it is a issue, it is a problem since i think ShowProducts
re-rendering is unnecessary because looking at the props i am passing to this components are arrayOfProducts
and a call back function to update how many times a item has been clicked / selected updateSelectedCount
.
I understand that every time selectedCount
changes a new instance of updateSelectedCount is generated so the ShowProducts component re-renders. But my question is why it should bother about the updateSelectedCount
being changed.
My question is how i can stop re-rendering <ShowProducts/>
keeping all the functionality intact.
Top comments (0)