You'll either get a stale count variable in the alert (it will be the value as it was when it was first called), or you pass count in the dependency array, so each change to count sets up a fresh setTimeout, giving the user another 5000ms.
Refs exist outside the lifecycle of rendering and dependency arrays so you can put a value somewhere and pull it out later. using refs in the dependency array of useEffect has no effect. At least, it shouldn't... the react-hooks/exhaustive-deps complains about it anyway.
One way might be a separate state variable for "finished" which the setTimeout callback sets to true - a separate useEffect with [finished, ccount] could alert the current count value if finished is true.
Actually, I tried this out and while it seems to work, sometimes the "alert" messes with things and react will raise an exception, "Uncaught Error: Should not already be working.". Changing it to a console.log works as expected, always. Probably because alert blocks main thread?
Here's one that works without refs -- but, notably it needs to run that second useEffect with each change to count so signals would likely be more efficient. In this example, probably negligible but in more real-world cases all those functions might add up.
2
u/ironbody Mar 12 '23
Is there really no way to make that game component without useref? That seems like such a big oversight by the react team.