Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"
  }}
>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading