Gotcha with Set Function

https://github.com/explorer436/programming-playground/tree/main/react-playground/25-use-state-gotcha

Keep in mind that the state update function setState does not immediately mutate the state. Instead, it schedules an update to the state and tells React that it needs to re-render the component. The actual state update will be performed as part of the next rendering cycle. Be mindful when you need to set state value based on a different state value.

If you want to update the state immediately and synchronously, you can pass a function to setState that receives the previous state as an argument and returns the new state. For example:

setState((prevState) => {
  return { ...prevState, value: newValue };
});

This can be useful if you need to update the state based on the previous state, or if you need to update the state synchronously.

const handleClick = () => {
  setValue((currentState) => {
    // must return otherwise undefined
    // below is the latest/current state value
    const newState = currentState + 1;
    return newState;
  });
};

Links to this note