0

I tried it in code sandbox, but Chrome firstly show 2 console.log and then alert.

We have the next component:

export default function Counter() {
  const [counter, setCounter] = React.useState(5);

  console.log("render");

  return (
    <>
      <span>{counter}</span>

      <button
        onClick={() => {
          console.log("click_1");
          setCounter(counter + 5);

          console.log("click_2");
          setCounter(counter + 5);

          alert(counter);

          console.log("click_3");
          setCounter(counter + 5);

          console.log("click_4");
          setCounter(counter + 5);
        }}
      >
        Increment
      </button>
    </>
  );
}

Why React firstly run alert, and after alert run console.log? Why React doesn't run 2 console.log and then alert?

What happens when we click on the button?

I know that React's asynchronous, but why first go alert and after console.log?

  • Likely because the console is being throttled. The function is called, sure, but you don't see the effect in the console before you get the synchronous alert. – AKX Jul 12 '23 at 09:50
  • I can't reproduce this. Copying your code into [a barebones react environment](https://playcode.io/1531058) shows me the first 2 console logs in the browser's console, before the `alert` pops up. – Cerbrus Jul 12 '23 at 09:51
  • It also depends on the browser you are using for example in firefox you will see things in order instead in chrome no ([link fiddle to test in both browsers](https://jsfiddle.net/w1nL8a0z/)) – Simone Rossaini Jul 12 '23 at 09:56
  • @SimoneRossaini FF and Chrome both work the same... – Cerbrus Jul 12 '23 at 09:57
  • You have some plugin/addon because i see exactly what OP said. – Simone Rossaini Jul 12 '23 at 10:06
  • The alert is executed immediately after calling setCounter(counter + 5) the first time because it's a 'synchronous' operation. Multiple state setters targeting the same state variable will get batched, scheduled and updated all at once 'asynchronously'. The console.log statements are executed during the subsequent re-render, after all the state updates have been processed 'asynchronously'. – Nazrul Chowdhury Jul 12 '23 at 10:15

0 Answers0