Why does Polaris use useCallback?

seandz
Excursionist
52 3 8
// documention example
function TextFieldExample() {
  const [value, setValue] = useState('Jaded Pixel');
​
  const handleChange = useCallback((newValue) => setValue(newValue), []);
​
  return <TextField label="Store name" value={value} onChange={handleChange} />;
}

I see this pattern across the docs. What advantage does it have over the simpler, more common pattern of passing an updated value straighto to useState() like so:

 

function TextFieldExample() {
  const [value, setValue] = useState('Jaded Pixel');
​
  return <TextField label="Store name" value={value} onChange={newValue => setValue(newValue)} />;
}
OTM
Shopify Expert
667 170 236

Hi, @seandz ,

This is Evita from On The Map.

 

It's not Polaris function, but React apps callback, you can read more about useCallback here - https://reactjs.org/docs/hooks-reference.html#usecallback

 

Best,
Evita

On The Map Marketing | Developing custom Shopify Sites & Apps is our thing

- Install our latest app Accessibly - Makes your store accessible for everyone, helps to avoid fines
- Inc 5000 | Shopify Parners | 20+ stores launched | 300+ active clients
- Need help with your Shopify store? Reach out to us!
0 Likes
seandz
Excursionist
52 3 8

Hi Evita, I know it's a React function but i was curious why your examples prefer it to a simpler useState() call? What advantages is there to doing it with the pattern in your examples?

jackcohub
New Member
1 0 2

I'm also curious about why this is so common in Polaris, any chance we could get an explanation for this?

Also curious about this as there doesn't seem to be a need to return a memoized callback function.

TrackPack

Gain shipment visibility, increase customer confidence and optimize your customer support using TrackPack's Email / SMS shipping notifications and order tracking page generator.
0 Likes