React Native: Variable state not updated on first click

Solution 1:

useState() hook changes the state asynchronously. so you can't make sure that the state will be changed immediately after calling setItemData() function.

Try useEffect to run a side effect whenever the state changes.

useEffect(() => {
  ToastAndroid.show("setItem: " + itemData, ToastAndroid.LONG);
}, [itemData]);

However, this code will show the toast on the component mount. to prevent it try something like this:

const isInitialMount = useRef(true);

useEffect(() => {
  if (isInitialMount.current) {
    isInitialMount.current = false;
  } else {
    ToastAndroid.show("setItem: " + itemData, ToastAndroid.LONG);
  }
}, [itemData]);