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

195
Vistas
Why is the React state not being updated properly?

I'm making a math game, and I'd like the range of the operands to be updated after a certain amount of questions. I have this code to set the difficulty

  const [difficulty, setDiff] = useState({rangeA:[1, 10], rangeB:[1, 10]});
  
  function setDifficulty(op) {
    let rangeA = [];
    let rangeB = [];
    if (question < 5) { //question state is incremented everytime the answer is correct, which triggers the next question
      rangeA = [0, 100];
      rangeB = [0, 10];
    }
    else if (question < 8) {
      rangeA = [0, 100];
      rangeB = [0, 100];
    }
    setDiff({...difficulty, rangeA, rangeB});
    console.log(rangeB, difficulty.rangeB); // when question is 5, this logs [0, 100] [0, 10], but they should be the same value [0,100]
  }

but the state doesn't update properly, what could be happening?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(difficulty)
   // Whatever else we want to do after the state has been updated.
}, [difficulty])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "difficulty" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info.

about 4 years ago · Santiago Trujillo Denunciar

0

When you call setDiff, the new value of difficulty will be updated during the next render. Since you are console.logging inside the setDifficulty function, before the render occurred, the reference to difficulty.rangeB still holds the value before the update.

about 4 years ago · Santiago Trujillo Denunciar
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