Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
React functional component: how to setState multiple times in a loop

In a loop, how to update the state as many times as the loop? For below, the updateDataset() only update the state when the loop finishes. Is there a way to update the state along with how many times the looping occur, so that the app re-render each round of looping

const [dataset, updateDataset] = useState([]);
function bubbleSort() {
        //how many rounds of comparison
        var sortedArray = dataset.slice();
        for (var i = sortedArray.length; i > 0; i--) {
            //how many comparison pair

            for (var j = 0; j < i - 1; j++) {

                // console.log(arr, arr[j], arr[j + 1]);
                //always compare one to the next one, that is why j+1

                if (sortedArray[j] > sortedArray[j + 1]) {

                    //swap the value
                    var temp = sortedArray[j];
                    sortedArray[j] = sortedArray[j + 1];
                    sortedArray[j + 1] = temp;
                    //update state
                    updateDataset(sortedArray.slice())
                   
                }

            }

        }

    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is there a way to update the state along with how many times the looping occur, so that the app re-render each round of looping

JS only has one event loop and blocking code (like a loop) is going to be The One Thing that JS is doing. Any state changes will be queued until the event loop is free.

What you could do is replace the loop with a recursive function which calls itself with a timer:

const example = (data, countdown) => {
    const newData = doStuffWith(data);
    if (countdown > 0) {
        setTimeout(example, 500, newData, countdown - 1);
    }
}

… but be very very careful you don’t end up with two instances of example running overlapped (from separate calls to whatever runs it for the first time).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!