开发者

using setState to getState in setInterval

开发者 https://www.devze.com 2022-12-07 22:44 出处:网络
I use this in a setInterva开发者_如何学Cl and it feels very illegal const [nonce, setNonce] = useState(0);

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);
}, []);
0

精彩评论

暂无评论...
验证码 换一张
取 消