I use this in a setInterva开发者_如何学Cl
and it feels very illegal
const [nonce, setNonce] = useState(0);
useEffect(() => {
window.setInterval(() => {
let nonce = 0;
setNonce((prevNonce) => (nonce = prevNonce));
console.log('nonce has the correct value even if got changed:', nonce);
}, 10);
}, []);
Is this something I should not use?
Nothing is wrong with it, but it needs to be cleaned up to avoid being re-rendered.
You have to store the variable and unset it on the return of your useEffect
hook.
In other words, if you don't do that, every time you "change page" in your application, you will create an extra interval.
This is how you clear your interval:
const [nonce, setNonce] = useState(0);
useEffect(() => {
// Store in a variable
const myInterval = setInterval(() => {
let nonce = 0;
setNonce((prevNonce) => (nonce = prevNonce));
console.log('nonce has the correct value even if got changed:', nonce);
}, 10);
// Clear it on return
return () => clearInterval(myInterval);
}, []);
精彩评论