itsaunix
itsaunix

Reputation: 41

How to pass arguments to useCallback

How in this example from the Shopify Polaris library (ReactJS)

function TextFieldExample() {
  const [value, setValue] = useState('Jaded Pixel');

  const handleChange = useCallback((newValue) => setValue(newValue), []);

  return <TextField label="Store name" value={value} onChange={handleChange} />;
}

is the argument newValue being passed to the useCallback?

I tried to lookup the source of the Polaris library but I couldn't come to a practical conclusion.

Edit: Maybe it would help to understand why this is necessary in React:

const useForceUpdate = ()
=> {
[value, setValue] = useState(0);

return () => setValue(value => value + 1);
}

To call this inside a component, I have to

const forceUpdate = useForceUpdate();
forceUpdate();

instead of just

useForceUpdate();

Upvotes: 0

Views: 341

Answers (1)

Oro
Oro

Reputation: 2586

useCallback returns a function that will be used in onChange prop. Inside TextField component props.onChange will be called when value will be changed. Somehing like this (just an example):

//TextField
function TextFiled(props) {
   const handleChange = (event) => {
      props.onChange(event.target.value); // here you function that was returned by useCallback
   }

   return <input onChange={handleChange}/>
}

Upvotes: 1

Related Questions