How would one update the value of variable simulationOn
inside of function executeSimulation
in the following context:
App this.state.simulationOn
changes via external code --> ... --> React stateless component (Robot
) rerendered --> useEffect
hook called with new values --> executeSimulation
IS NOT UPDATED with new value of simulationOn
.
function Robot({ simulationOn, alreadyActivated, robotCommands }) {
useEffect(() => {
function executeSimulation(index, givenCommmands) {
index += 1;
if (index > givenCommmands.length || !simulationOn) {
return;
}
setTimeout(executeSimulation.bind({}, index, givenCommmands), 1050);
}
if (simulationOn && !alreadyActivated) {
executeSimulation(1, robotCommands);
}
}, [simulationOn, alreadyActivated, robotCommands]);
}
In the example above, simulationOn
never changes to false
, even though useEffect is called with the updated value (I check with console.log). I suspect this is because the new value of simulationOn
is never passed to the scope of function executeSimulation
, but I don't know how to pass new hook values inside of function executeSimulation
.
The executeSimulation function has a stale closure simulationOn will never be true, here is code demonstrating stale closure:
Note that
Robot
is called every time it renders butexecuteSimulation
runs from a previous render having it's previoussimulationOn
value in it's closure (see stale closure example above)Instead of checking
simulationOn
inexecuteSimulation
you should just startexecuteSimulation
whensimulationOn
is true and clearTimeout in the cleanup function of the useEffect: