reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
10.86k stars 7.45k forks source link

[Suggestion]: Section "Queueing a Series of State Updates": await in event handler cause immediate rerender #6931

Open 0815Hunter opened 3 weeks ago

0815Hunter commented 3 weeks ago

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.