React: useState with function as argument

Have been watching John Smilga’s amazing 10hrs tutorial for a while, and in the Functional Update Form module I saw him writing something like this to use the previous state in an async call:

setTimeout(()=>{
      setValue( prevState => prevState + 1)
}, 2000)

Now: prevState has never been defined anywhere else in the code, so how does the callback get the current state value (or how does prevState get populated with one, which is the same)? Is there something at work similar to a .forEach call in JS, where the forEach function assumes that if you use only one parameter in its callback the parameter will be the nth item in that particular loop, if you use two the second will be an index of the array passed, corresponding to the item?

I mean: the only way I understand it now is that the function passed into setValue in the above code gets its parameter from setValue itself.

Is that correct?
(I tried looking in the docs, but could not find an answer )

the setter can either take a value to set the state to something else or it can take a callback, and the param is the old state and you can do things to it in the function.

[one, setOne] = useState(1);
setOne(2);
console.log(one) // 2;
setOne(num => num + 1);
console.log(one) // 3;
1 Like

Ok, so my guess was right.

I went back to check again in the docs and the tutorial and I am surprised not to find it explicitly explained as you just did. I might have missed it, of course, but it seems quite important to me.

Anyway: thanks!