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

255
Views
When to update state based on previous state in useState hook in React/Typescript

I have seen quiet a few examples on how to update state based on previous state, but I don't see much explanation on when to update state based on previous state, most examples use a counter example, but what if I was setting a object in state, would this still be based on the previous value or can I just update the state. e.g

const exampleData = [
    {
       text: 'Example name',
       value: 1
    },
    {
       text: 'Example name 2',
       value: 2
    }
]

  const [asset, setAsset] = useState(exampleData[0]);

  const handleClick = (event) => {
      setAsset(event.target.value) 
  }

So in the example I am updating the state in the handleClick function, but would I need to update it based on the previous value or not?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you want to access previous state, avaiable in setState action

const [state, setState] = useState(false);

const handleClick = () => {
    setState(prev => !prev); // true
    setState(prev => !prev); // false
}

Notice: setState is async action

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!