Javascript Increment Counter on Button Click using React

Spread the love

In this article, I am going to share code for the Javascript Increment Counter on Button Click using React. I have been using the React environment to implement this function as most of the jobs are asking for a React skill set.

Javascript Increment Counter on Button Click using React

import React, { useState, useEffect } from "react";

export default function App() {
  const array = ["a", "b", "c", "d", "e", "f", "g"];
  const arrayLength = array.length;
  const [counter, setCounter] = useState(-1);
  const [value, setValue] = useState("");
  const [pauseValue, setPauseValue] = useState(0);
  let timeout;

  useEffect(() => {
    if (counter > -1) {
      timeout = setTimeout(() => {
        if (counter < arrayLength) {
          setValue(array[counter]);
          setCounter(counter + 1);
        } else {
          setCounter(0);
        }
      }, 1000);
    }
  }, [counter, arrayLength]);

  const start = () => {
    if (pauseValue > 0) {
      setCounter(pauseValue);
    } else {
      setCounter(counter + 1);
    }
  };
  const pause = () => {
    clearTimeout(timeout);
    setPauseValue(counter);
    setCounter(-1);
  };

  return (
    <div className="App">
      <p>{value}</p>
      <button onClick={start}>Start</button>
      <button onClick={pause}>Pause</button>
    </div>
  );
}

Explanation:

Writing an increment function on the counter might be a little easier comparatively but I wanted to implement this functionality on the array of strings because that would be similar to a real use case in our projects.

So, I took the array of strings initially, and I directly ran setTimeout inside the useEffect hook with the dependencies counter and arrayLength. This will do the job without any external intervention like clicking.

The challenging part was to trigger this increment function at the click of a button, pausing the loop on clicking the pause button, and again restarting the loop from the current counter value at the click of the start button.

For this purpose, I need to initialize the counter with -1 so that I can write conditions inside the start function to trigger this function on clicking. When I increment the counter inside the start function, this will trigger the setTimeout inside useEffect.

When I click on the pause button, I should store the current counter value because when I click on start again, the counter should continue from the current counter value. For this, I have used the variable pauseValue to store the current counter state. We need to clear the timeout method inside the pause function to restart the increment when we click on the start button.

I have added a condition in the start function with pauseValue to determine the click of start after a pause.

So, in this way, we can implement an increment function on the click of a button using javascript and react.

 

Leave a Comment