Bug: inconsistent auto batching

This issue has been tracked since 2022-09-15.

I have to useEffects in my code. in first one I have two setState, the second one is in then of Promise.resolve.
and in the second useEffect I make a request by apollo client.

React version: 18.2.0

Steps To Reproduce

  1. rerun app to see different logs

Link to code example:
https://codesandbox.io/s/confident-http-m4fey5?file=/src/App.js:623-641

The current behavior

In some run the output of logs is:
image
and in some other run:
image

The expected behavior

I expected react to does not batch setState("bb") and setState("aa") at all and always logs like this:
image

but I don't know why react in some run batch two setStates and in some other run doesn't batch. I don't know there is any problem with apollo because with fetch react always doesn't batch these to setStates

LuBustos wrote this answer on 2022-09-19

Hey @amirqasemi74! I think the problem is that every fetch takes differents times so the logs are differents, if you try to make a promise and get the same data as the Apollo fetch, you will have your expected behavior. Anyways you can use a setTimeout if one promise takes more time than other.
Here is an example:

  const run_1 = async () => {
    setA("aa");
    await Promise.resolve().then(() => {
      setTimeout(() => {
        console.log("here");
        setB("bb");
      }, 50);
    });
  };

I hope I've helped you 😊

More Details About Repo
Owner Name facebook
Repo Name react
Full Name facebook/react
Language JavaScript
Created Date 2013-05-24
Updated Date 2022-10-05
Star Count 195628
Watcher Count 6648
Fork Count 40518
Issue Count 1111

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date