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

127
Vistas
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 Respuestas
Responde la pregunta

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 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