Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda