Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
0815Hunter opened this issue Jun 5, 2024 · 1 comment

Comments

@0815Hunter
Copy link

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.

@0815Hunter 0815Hunter changed the title [Suggestion]: Section "Queueing a Series of State Updates": await in event handler cause rerender [Suggestion]: Section "Queueing a Series of State Updates": await in event handler cause immediate rerender Jun 5, 2024
@JZZICK
Copy link

JZZICK commented Oct 30, 2024

Can i try this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants