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

96
Visualizações
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
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