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

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
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