In the below code snippet, the component is rendered thrice when user clicks on the button but the count values remain the same.
import React, { useEffect } from 'react';
const wait = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
export default function App() {
const [count, setCount] = React.useState(0);
useEffect(() => {
console.log('rerendered');
console.log(count);
});
const inc = async () => {
setCount(count + 1);
setCount(count + 5);
await wait();
console.log(count);
setCount(count + 1);
console.log(count);
setCount(count + 2);
console.log(count);
};
return (
<div>
<h1>{count}</h1>
<button onClick={inc}>Increment</button>
</div>
);
}
I know that first two setCount()
are batched and after await
they are not batched. If I use setCount(prev => prev +1)
, I will get the updated values but my question is
Why are the count
values different in inc()
and useEffect()
? When does the count
value actually changes coz certainly not on re-render?