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

95
Views
React useState Hook not updating state correctly

I am working on a Memory Game Project in React. I have an array of pokemon objects (since I use those as input for the game) and I set the nextPokemon in state to be an object at a random index in said pokemonsArray. Afterwards, I am adding the nextPokemon to an array called renderedPokemon, which I map over in the render function and create a button for every one of them. Now I already found out that if I have multiple state setters in one place, they get batched together and therefore it makes sense for my renderedPokemon array to receive an empty object when I add nextPokemon to it, because nextPokemon hasn't been evaluated yet. I added my code at the bottom, because I still have issues with a lot of it, which is:

a) understanding why setNextPokemon doesn't work, because it is the first process in line and doesn't even rely on previously set state, therefore batching it together with other state setters shouldn't be an issue

b) getting to know how updater functions help me since in setRenderedPokemon, using for example "prev => prev + x" doesn't help - I don't rely on previous values from the same state but from another state

You can see the code below. Any help is be appreciated.

const [pokemonsArray, setPokemonArray] = useState(pokemons);
const [score, setScore] = useState(0);
const [renderedPokemon, setRenderedPokemon] = useState([]);
const [nextPokemon, setNextPokemon] = useState({});

useEffect(() => {
     for (let i = 0; i < 9; i++) {
          if (score === 49) {
             return
          } else if (renderedPokemon.length == 0) {
                    setNextPokemon(pokemonsArray[Math.floor(Math.random() * 49)]);
                    setRenderedPokemon(nextPokemon);
          }
     }
}

about 4 years ago · Juan Pablo Isaza
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!