Search code examples
reactjsincrement

React JS - How to increment a number from 1 to 9 minutes per minute?


How to increment a number from 1 to 9 minutes per minute? I need to increment a number from one to nine every minute. After going through the nine numbers, go back to the beginning.

I need to change a className per minute. I try this:

const [count, setCount] = useState(1);

useEffect(() => {
    const timer = setTimeout(() => incrementCount, 3000);
    return () => clearTimeout(timer);
  }, []);

  
  const incrementCount = () => {
    setCount(count + 1);
  };

  const name =  `C${count}`;

Now the className is C1, but after a minute I need C2...


Solution

  • The code you provided basically works. It just needed some tweaks:

    1. you forgot to add brackets to incrementCount in setTimeout
    2. you need to but the handler in the useEffect or maybe in a useCallback, because the way you did it the renderer would recreate the callback on each render
    3. you need to add count to the dependencies of useEffect, but this is only the case if you move the callback incrementCount into the useEffect

    here is a working example code