Dealing with Stale States

Any function inside a component, including event handlers and effects, “sees” the props and state from the render it was created in.

If you first click “Show alert” and then increment the counter, the alert will show the count variable at the time you clicked the “Show alert” button.
RESETRUNFULL
function Example() {
   const [count, setCount] = React.useState(0);
   function handleAlertClick() {
      setTimeout(() => {
         alert('You clicked on: ' + count);
      }, 3000);
   }
   return (<div><p>You clicked {count} times</p>
                       <button onClick={() => setCount(count + 1)}>
                          Click me
                       </button>
                       <button onClick={handleAlertClick}>
                          Show alert
                       </button>
              </div>);}ReactDOM.render(<Example/>,document.querySelector("div"));
If you intentionally want to read the latest state from some asynchronous callback, you could keep it in a ref.
RESETRUNFULL
function Example() {
  const [x,setX] = React.useState(0)
  const count = React.useRef(0);
  function handleAlertClick() {
    setTimeout(() => {
      alert('You clicked on: ' + count.current);
    }, 3000);
  }
  return (
    <div>
      <p>You clicked {count.current} times</p>
      <button onClick={() => {count.current++; setX(x=>(x+1))}}>
        Click me
      </button>
      <button onClick={handleAlertClick}>
        Show alert
      </button>
    </div>
  );}ReactDOM.render(<Example/>,document.querySelector("div"));