0

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?

1 Answer 1

1

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);
}, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.