I know what a closure is but I don't understand how actually useEffect capture the variable as opposed to a similar code I have.
For example , looking at this example : https://codesandbox.io/s/bold-sinoussi-ff42j?file=/src/index.js
function longResolve() {
return new Promise(res => {
setTimeout(res, 3000);
});
}
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
longResolve().then(() => {
alert(count);
});
}, []);
The output of the alert here is 0 , no matter how many times value is increased by a user.
However , I've tried to simulate it with my own code : https://jsbin.com/yocazeqese/1/edit?html,js,console
let count = 0;
function useEffect()
{
function longResolve()
{
setTimeout(() => console.log(count), 1000) //investigating value after longer time
}
longResolve()
setTimeout(() => count=6, 100) //user changed value after 100ms
}
useEffect();
But here the value is 6 rather than 0.
I already know that if I do IIFE on the longResolve I will get the 0. But that's not my question.
My question is : structure-wise , both samples are similar so how come useEffect does capture in closure the value ?