I have a simple function as below. I understand setState run as an async function, therefore the result should like:
1
3
2.1
2.2
............
But in the first Click, the result is:
1
2.1
3
2.2
..............
Means that the first setCount executed in a sync way, and for all the next Clicks, the code run normally (
1
3
2.1
2.2
............). Can I ask why this behavior happens? Thanks.
const [count, setCount] = React.useState(1);
const handleClick = () => {
console.log('1');
setCount((prevCount) => {
console.log('2.1');
return prevCount + 1;
});
setCount((prevCount) => {
console.log('2.2');
console.log('------------');
return prevCount + 1;
});
console.log('3');