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

120
Visualizações
Previous state in a useState functional component

I need to rotate an element based on user's input. The thing is that in my functional component I'm using useState hook to store and update the value that user typed but the element gets rotated not based on the last input but on the one before that.

I recreated the simplified example in CodeSandbox to illustrate the issue.

How do I make it work properly in a functional component?

https://codesandbox.io/s/strange-clarke-nlyuo?file=/src/App.js:0-762

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should not be reaching into the DOM to set the transform. You should remove the querySelector line from your input.

<input
  type="number"
  max={359}
  value={value}
  onChange={(e) => {
    setValue(e.target.value);
    // don't do this 👇
    document.querySelector("h1").style.transform = `rotate(${value}deg)`;
  }}
/>

The state change will trigger a re-render, so just set the transform during render:

<h1
  style={{
    transform: `rotate(${value}deg)`,
    border: "1px solid pink",
    display: "inline",
    padding: "10px"
  }}
>
about 4 years ago · Juan Pablo Isaza 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