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

174
Views
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 answers
Answer question

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