-
Notifications
You must be signed in to change notification settings - Fork 47.5k
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
Bug: setState inside setInterval runs async first and then sync #32265
Comments
Could you please double-check whether the sandbox is marked as public?
|
Dumb move. Made the change. |
I checked and what I found is on first rendering or on Mounting of react component the log inside setState() always gets executed first and then for next renders the behavior is again normal . In your case for first two times it is behaving synchronously because for first time your count value is not changing it is still zero so there is no re-render and it prints synchronously, for second time the count value changes first time but since it is re-rendering for first time it is still behaving synchronously, after that when count is updated the behavior is normal again. Try changing your initial value of i=1 it will behave like that only for first iteration or first re-render that I was saying above. What I am not able to understand is why for every first render it is behaving synchronously and then async. It is for first time only not sure why? |
Yes, I am aware of the behaviour. Only the first render is behaving differently. Still do not understand why and could not find any relevant docs pointing towards this. |
I tested it, I believe it's due to the batching of state changes in react, when I force the synchronous state changes using flushSync, this won't happen. |
Yes, React 16 behaves consistently. So it has to do with the batching React 18 introduced i assume |
React version: 19
Steps To Reproduce
Link to code example: https://codesandbox.io/p/sandbox/amazing-rain-forked-5knv6z?workspaceId=ws_XcXHczGEnBvM34o6MyJMXt
The current behavior
In the initial iteration the setState callback is called synchronously but later it is called asynchronously.
The expected behavior
setState to behave same in all iterations.
The text was updated successfully, but these errors were encountered: