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
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…