The set function only updates the state variable for the next render. If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call. Calling the set function does not change the current state in the already executing code:
Here, a => a + 1 is your updater function. It takes the pending state and calculates the next state from it. React puts your updater functions in a queue. Then, during the next render, it will call them in the same order:
React always makes sure that for intentional user actions, like clicks, the age state variable is updated before the next click. This means there is no risk of a click handler seeing a “stale” age at the beginning of the event handler.
If the new value you provide is identical to the current state, as determined by an Object.is comparison, React will skip re-rendering the component and its children. This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn’t affect your code.
React batches state updates. It updates the screen after all the event handlers have run and have called their set functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use flushSync.
Calling the set function during rendering is only allowed from within the current rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to store information from the previous renders.