based on the https://stackoverflow.com/a/73115899/21769004 and the example from https://legacy.reactjs.org/docs/hooks-state.html, below is valid code:
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
What if I click the button twice very quickly, so first click calls setCount(count + 1)
and because React's state change apply asynchronously, so count
is still 0 (after the first click) at the moment, then I click the button again within 5 millisecond, and the second click calls setCount(count + 1)
, since the first update hasn't been applied, so the count
still 0, and the second click uses the stale count
value, therefore it shows "You clicked 1 times" instead of "You clicked 2 times".
Is my understand correct? is the reason that we still get correct results because we cannot make a consecutive click within tiny millisecond, but theoretically if we can make consecutive clicks faster enough then the code could be a bug?