Home > Blockchain >  using setState to getState in setInterval
using setState to getState in setInterval

Time:12-07

I use this in a setInterval 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?

CodePudding user response:

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