React SetState callback is synchronous

Viewed 31

I have a simple react component and iam playing with the state a little bit.

I noticed when i pressed the button, the "first" executes along with "inside1". Afterwards "second" and then "HEYY STATE". I thought that setState executes asynchronously but it seems that the first one executes synchronously.

Why only the first callback is executed synchronously?

On React 17v.

const Test= () => {

  const [test, setTest] = useState(0);

  console.log("HEYY STATE", test);

  return (
    <button
      type="button"
      onClick={() => {
        setTest((e) => {
          console.log("first", e);
          return 1;
        });

        setTest((e) => {
          console.log("second", e);
          return 2;
        });
        console.log("inside1");
    
      }}
    >
      Hello
    </button>
  );
};
0 Answers
Related