I'm based on the React Docs write a setInterval in the useEffect,
i wants start a timer when app is mounted,
the recommended writing is:
const [a, setA] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setA(x => x + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
When there is needs some dependency,i've been advised to use useState's callback function for avoid dependency, but when i needs another state b,it's the condition of a's self-increment.
like:
const [a, setA] = useState(0);
const [b, setB] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setA(x => {
if (b > 5) {
return x;
}
return x + 1;
});
}, 1000);
return () => clearInterval(timer);
}, []); // dependency error, that required dependency b
To fix this problem, i combined state a and b,like:
const [c, setC] = useState({
a: 0,
b: 0,
});
useEffect(() => {
const timer = setInterval(() => {
setC(x => {
if (x.b > 5) {
return x;
}
return { a: x.a + 1, b: x.b };
});
}, 1000);
return () => clearInterval(timer);
}, []);
Is this the right way to write it, or should I use useEffectEvent?
Top comments (0)