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

166
Views
useState setState not updating the state after calling setState

In my react project, using useState hook's setState is not changing my state value, after calling setState.

const [name, setName] = useState("Old");

useEffect(()=>{
    setName("New");

    console.log(name);  //Always prints "Old"
})

I tried adding a callback to setName, but it wouldn't accept that too.

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

0

I finally used the useEffect hook

Since setState is asynchronous, it was not updating the state immediately on call, it rather initiates the process of changing the state and javascript proceeds to execute to the lines below.

So I ended up using useEffect hook to execute anything that I wanted to run after the state name is changed, adding the state name as a dependency as shown below.

const [name, setName] = useState("Old");

useEffect(()=>{
    setName("New");
})


useEffect(()=>{

    console.log(name);  // This Always gets the new value
}, [name])
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!