Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda