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

140
Views
How to fill a state with an array

I'm trying to add a list inside a state using the set method, but my state remains empty

App.js

// Starts the screts word game
  const startGame = () => {
    // pick word and pick category
    const { word, category } = pickWordAndCategory();
    // create array of letters
    let wordLetters = word.split("");
    wordLetters = wordLetters.map((l) => l.toLowerCase());

    // Fill states
    setPickedCategory(category);
    setPickedWord(word);
    setLettersList(wordLetters);
    console.log('wordLetters', wordLetters);
    console.log('lettersList', lettersList);
    

    setGameState(stages[1].name);
  };

  const pickWordAndCategory = () => {
    // pick a random category
    const categories = Object.keys(words);
    const category = categories[Math.floor(Math.random() * Object.keys(categories).length)];
    console.log('category', category);

    // pick a random word
    const word = words[category][Math.floor(Math.random() * words[category].length)]
    console.log(word);

    return { word, category };
  }

Here is the browser log

When looking at the log we find our state empty

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

State updates are asynchronous, so when you set a new state value and console.log() right after it, it will return the old value, because the state hasn't been updated yet.

That's why your lettersList value shows the previous value of the state in the console (empty array).

about 4 years ago · Santiago Gelvez Report

0

When you use setLettersList(...), you are not actually changing lettersList variable itself. Notice how when you declare it, const [lettersList, setLettersList] = useState([]); letterList is actually constant, so that variable can't even be changed. Instead, it tells React to rerun the function component, this time giving lettersList the new value. Therefore, for the updated value, it will only come once const [lettersList, setLettersList] = useState([]); is rerun again from the entire function being rerun again.

If you want to monitor changes to lettersList, you can do:

useEffect(() => {
  console.log(lettersList);
}, [lettersList]);

This will print lettersList every time it is updated.

about 4 years ago · Santiago Gelvez 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!