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

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

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 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