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
?