Unable to understand how useCallback prevents re-renders

27 Views Asked by At

I am learning about useCallback from React's Beta docs. I re-created the example shown in the docs but I am unable to prevent any re-rendering by using useCallback and memo.

If you click on any product, the Shipping component is getting re-rendered anyway (check console.log's output in the debugger console) even after using memo and passing a prop which is cached using useCallback.

What am I doing wrong?

Stackblitz Link: https://stackblitz.com/edit/react-ts-nec41u?file=Shipping.tsx

1

There are 1 best solutions below

0
Free Me On

If you click on a product, then the productId changes. Since productId is in the dependency array of useCallback, it will cause the handleSubmit to be created again. And since handleSubmit, the props of Shipping changes, the component is rerendered. If you removed the productId from the array, then Shipping would not longer rerendered, but in that case the function will work incorrectly.