R
Reactiflux

react-forum

setInterval without destroying it to update state?

PPoppingPopper10/8/2022
I have a perdicament where I want to update state on an interval. Every way that I go about it I find myself being forced to use the dependency array of the useEffect for the setInterval so I can get updated state values. This causes my interval to just be destroyed and rebuilt every interval because of state changing on the interval. How can I achieve this interval without ever having to destroy it to listen to state changes?
const [incrementCount, setIncrementCount] = useState(1);
const [translationX, setTranslationX] = useState([...INIT_TRANSLATION_X]);

const incrementTranslationX = useCallback(() => {
if (incrementCount && incrementCount % 2 === 0) { //* the condition
setIncrementCount(0);
setTranslationX([...INIT_TRANSLATION_X]);
} else {
setIncrementCount((prev) => prev + 1);
setTranslationX((prev) => [prev[0] + INCREMENT, prev[1] + INCREMENT]);
}
}, [incrementCount, translationX]);

//loop interval
useEffect(() => {
const interval = setInterval(() => {
incrementTranslationX();
}, INTERVAL);

return () => {
clearInterval(interval);
console.log("DESTROYED INTERVAL");
};
}, [incrementTranslationX]); //! cannot update (the condition) without this
const [incrementCount, setIncrementCount] = useState(1);
const [translationX, setTranslationX] = useState([...INIT_TRANSLATION_X]);

const incrementTranslationX = useCallback(() => {
if (incrementCount && incrementCount % 2 === 0) { //* the condition
setIncrementCount(0);
setTranslationX([...INIT_TRANSLATION_X]);
} else {
setIncrementCount((prev) => prev + 1);
setTranslationX((prev) => [prev[0] + INCREMENT, prev[1] + INCREMENT]);
}
}, [incrementCount, translationX]);

//loop interval
useEffect(() => {
const interval = setInterval(() => {
incrementTranslationX();
}, INTERVAL);

return () => {
clearInterval(interval);
console.log("DESTROYED INTERVAL");
};
}, [incrementTranslationX]); //! cannot update (the condition) without this
Solution:
Looks like the answer I'm looking for is to not read state at all and instead use local values.
Jump to solution
UUUnknown User10/8/2022
Message Not Public
Sign In & Join Server To View
Solution
PPoppingPopper10/8/2022
Looks like the answer I'm looking for is to not read state at all and instead use local values.
UUUnknown User10/8/2022
Message Not Public
Sign In & Join Server To View
Aaprillion10/9/2022
or read someRef.current from inside an interval

Looking for more? Join the community!