I want my aysnc function to react to state change so that it can terminate upon state change. What I have discovered is that it doesn't react to changing the state.
In the provided example I am changing the state from inside of the function, however I have tested it and changed the state from outside of function (Button click) and it doesn't work either.
const [testVariable, setTestVariable] = useState(false);
useEffect(()=> {
testFunction();
}, [])
const testFunction = async () => {
await timeout(1000);
console.log("Setting test variable to: " + true);
setTestVariable(true);
await timeout(1000);
console.log("Test variable is: " + testVariable);
}
Expected result is to see that the variable changed to true, however what I see is:

State variables never change their values. (Note that you can, have, and should declare them with const because they don't change).
Subsequent invokes of the component function will get a new state variable with the same name and a different value.
Your testFunction function has closed over the old state variable.
I suspect you could solve this with a reference:
const [testVariable, setTestVariable] = useState(false);
const reference = useRef();
reference.current = testVariable;
… and then have your function test the value of reference.current instead of testVariable.
This does, however, feel like an XY Problem where the real solution is "Use the return value from the function you pass to useEffect to stop whatever it is you want to stop" (and use testVariable as a dependency of useEffect).
state update in react is async means that your state will be changed in next render cycle. you can useEffect hook to track if any state is changed or not.
useEffect(() => {
console.log(testVariable);
}, [testVariable]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With