title: React component not getting rendered each time when state changed
body: <p>I am trying to sort an array using bubble sort and at each step of sort I want to render the change in position of values inside an array.
  So made the below algorithm with React, at very first time it does render the changes but then gets stop, doesn't render anything. I tried to console log the array I am rendering in and I am getting the each sort step on console but don't know why it is not working here.
  Can anybody please tell me why it's happening so? also what can be done?</p>
  <p>Note: It was working fine and rendering the sorted array initially, but later when I added <code>setTimeOut</code> function it is not working.</p>
  <p>App.js</p>
  <pre><code>import React, { useState } from &quot;react&quot;;
  
  const App = () =&gt; {
    const [arrayForSort, setArrayForSort] = useState([44,2,46,11,15,34,1,7,55]);
  
    const fetchArray = arrayForSort.map((element) =&gt; {
      return &lt;span&gt;{element} &lt;/span&gt;;
    });
  
    const bubbleSort = (array) =&gt; {
      let newArray = [...array];
      let n = newArray.length;
  
      for (let i = 0; i &lt; n; i++) {
        for (let j = 0; j &lt; n - i; j++) {
          const myVar = setTimeout(() =&gt; {
            if (newArray[j] &gt; newArray[j + 1]) {
              [newArray[j], newArray[j + 1]] = [newArray[j + 1], newArray[j]];
            }
            console.log(newArray);   // render each step of sort 
            setArrayForSort(newArray);   // on screen it just shows &quot;2 44 46 11 15 34 1 7 55&quot; the very first step of sort
          }, 2000);
        }
      }
    };
  
    return (
      &lt;div&gt;
        &lt;h4&gt;Array: &lt;/h4&gt;
        &lt;span&gt;{fetchArray}&lt;/span&gt;
        &lt;div&gt;
          &lt;button
            onClick={() =&gt; {
              bubbleSort(arrayForSort); 
            }}
          &gt;
            Sort
          &lt;/button&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  };
  
  export default App;
  
  </code></pre>