Creating a counter in React using setInterval

omkargarde

omkargarde

Posted on April 15, 2024

Creating a counter in React using setInterval

This is example of how a regular react counter is made, here value of the counter is increased based on button clicks

function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <button 
         onClick={() => setCount((count) => (count + 1))}>
           count is {count}
      </button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

To increase the value of count based every second we need use setInterval() hook and not setTimeout() because of the way React rerender

This is the code for counter based on interval

const App = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount((prevCount) => Math.min(prevCount + 1, 30));
    }, 1000); // Update every second

    return () => clearInterval(intervalId);
  }, []);

  return (
    <div>
      <h1>Count: {count}</h1>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

so what does the code do exactly?

useEffect is used to setup the interval and perform clean up of interval when component unmount during rerender

setInterval takes two arguments a callback and interval for when to call the callback and return a id

clearInterval takes a single argument which is id returned by setInterval and clear the callback during unmount so that it does not interfere during the next render cycle

đź’– đź’Ş đź™… đźš©
omkargarde
omkargarde

Posted on April 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related