0

I have an array and I basically want one element in this array to count up on the screen. It however is not changing from its initial state [0,0,0,0,0] on the screen. However, when I console.log my test variable, it does indeed increment from [0,0,0,0,0] to [0, 10, 0, 0, 0] every 0.1 seconds. My problem is that my DOM does not show this counting up effect ~ it shows no change at all. This works when I do not have an array, and use a single number. The Following is my code:

import React, { useState } from "react";

function App() {

  const [test, setTest] = useState([0,0,0,0,0]);

  const handleCount = () => {
    let a = test;
    for (let i = 0; i < 10; i++) {
      setTimeout(() => {
        a[1] += 1
        setTest(a);
        console.log(test);
      }, 100 * i);

    }
  };

  return (
    <div className="App">
      <h1>{test}</h1>
      <button onClick={handleCount}>
      Countup
    </button>
    </div>
  );
}

export default App;
  • You are setting the **same** array over and over again. React doesn't do deep object comparison. If object ref is the same the state is considered unmodified. – Yury Tarabanko Sep 28 '22 at 16:36

0 Answers0