AiKw
AiKw

Reputation: 39

React setState in a loop with time delay is not triggering rerenders

I'm trying to mimic a simple sorting algorithm and use React setState to store the sorted array (as "output") in real-time with an interval of 100ms so it can show on the screen as an algorithm visualizer. The sorted array can be displayed in the console but the React state is not updating real-time accordingly. How can I fix this?

  const [output, setOutput] = useState([]);

  const timer = (ms) => new Promise((res) => setTimeout(res, ms));

  const Simple_Sorting_Algo = (n) => {
    const array = [];
    for (var i = 0; i < n; i++) {
      array.push(Math.floor(Math.random() * 1000));  //generating a random array
    }

    const sortedArr = [...array];
    const send = async () => {
      for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
          if (sortedArr[i] > sortedArr[j]) {
            var tmp = sortedArr[i];
            sortedArr[i] = sortedArr[j];
            sortedArr[j] = tmp;           
            console.log(sortedArr);
            setOutput(sortedArr);
            console.log(output);
            await timer(100);     //delay
          }
        }
      }
    };
    send();
  };

Upvotes: 1

Views: 762

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

You have to update the state immutably.

setOutput(sortedArr) should be setOutput([...sortedArr])

Edit keen-andras-gpfq3

The sort function mutates the array in each iteration which is fine, but you can't use the mutated array for updating the state because React doesn't rerender the component when it receives the same array every time.

Upvotes: 3

Related Questions