Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!