Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda