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

171
Vistas
React updating state inside for loop

How works useState under the hood if I put it inside for loop. From below code snippet I getting list of only one element. console.log(names) prints 3 times value of names:

first render -> null

second and last render -> complete array (10 elements)

I know that setNames should be placed outside for loop, but I wonder why it render array 3 times (i expected only 2) and why I getting ul/li list of only 1 element insted of 10.

const {useState, useEffect} = React;

const url = 'https://api.github.com/users';

const Example = () => {

    let [names, setNames] = useState(null)
    let list = []

    const getNames = async () => {
        let response = await fetch(url)
        let users = await response.json()
        for (let i = 0; i < 10; i++) {
            list.push(users[i].login)

            setNames(list)
        }
    }

    useEffect(() => {
        getNames()
    }, [])

    console.log(names);

    return (
        <ul>
            {names && names.map((item, index) => {
                return (
                    <li key={index}>{item}</li>
                )
            })}
        </ul>

    )
};

ReactDOM.render(
  <Example/>,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this. Add users first in a list and after the loop, update the state.

const getNames = async() => {
  const response = await fetch(url)
  const users = await response.json()
  let names = []
  for (let i = 0; i < 10; i++) {
    names.push(users[i].login)
  }

  setNames(names)
}

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