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

Bug: setState re-renders the component synchronously when called in a promise #21352

Closed
KarelHrkal opened this issue Apr 26, 2021 · 1 comment
Labels
Resolution: Expected Behavior Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@KarelHrkal
Copy link

React version: 16.13.1

Steps To Reproduce

  1. Call setState in an asynchronous function after await, or in a .then() function on a promise.

Link to code example: https://codesandbox.io/s/friendly-ganguly-gsl6c?file=/src/App.js

Code example

const SynchronousRerender: FunctionComponent = () => {
  const [value, setValue] = useState(0);
  console.log('I am rendering with value = ', value);

  useEffect(() => {
    Promise.resolve().then(() => {
      console.log('Use effect 1');
      setValue(1);
      console.log('Use effect 2');
      setValue(2);
      console.log('Use effect 3');
      setValue(3);
      console.log('Use effect done');
    });
  }, []);

  return <>{value}</>;
};

The current behavior

Calling setState will synchronously re-rendener the component - the component function will be called with the new state before setState even returns. The code example prints:

I am rendering with value =  0
Use effect 1
I am rendering with value =  1
Use effect 2
I am rendering with value =  2
Use effect 3
I am rendering with value =  3
Use effect done

The expected behavior

The new state should be queued for an update and then processed afterwards, preferably the same way as if it wasn't in a .then() promise function: all the state changes get evaluated, and then the component is re-rendered only once. The code example should print:

I am rendering with value =  0
Use effect 1
Use effect 2
Use effect 3
Use effect done
I am rendering with value =  3
@KarelHrkal KarelHrkal added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 26, 2021
@eps1lon
Copy link
Collaborator

eps1lon commented Apr 26, 2021

Thanks for the report.

A similar issue was reported in #20991. #20991 (comment) hopefully gives a good entrypoint to understand that the reported behavior is expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Resolution: Expected Behavior Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

2 participants