react.dev
react.dev copied to clipboard
[Suggestion]: Section "Queueing a Series of State Updates": await in event handler cause immediate rerender
trafficstars
Summary
The documentation says here: "React waits until all code in the event handlers has run before processing your state updates"
This not the case when using await inside the handler!
Example
const [myNumber, setMyNumber] = useState(0);
async function handleClick(){
setMyNumber(i => i + 1);
await delay(100);
setMyNumber(i => i + 1);
}
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
This will rerender the component twice!
Page
https://react.dev/learn/queueing-a-series-of-state-updates
Details
I suggest it should be mentioned as caveat/pitfall that if you call await inside an event handler,
all changes made to states before that await will then be flushed and trigger a rerender immediately, not waiting
for the event handler to finish completely.