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

147
Views
Why is setState not updating my state value?

function LoginComponent(){
  const [clicked, setClicked] = useState(false)
  
  function handleClick(){
    console.log('before', clicked)
    setClicked(true)
    console.log('after', clicked)
  }
  return(
    <a onClick={handleClick}>
      random text
      </a>
  )
}

When I run this, the console outputs before false after false. Why is this? I have no clue why this behavior is like this.

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

0

Because setting state is an asynchronous action. It takes some time to update. Check react documentation link to know more

You can check the updated value by

    useEffect(()=> { 
         console.log("clicked", clicked);
 },[clicked]);
about 4 years ago · Juan Pablo Isaza Report

0

There are couple of reasons for this behavior:

  • State is updated asynchronously
  • In any particular render, state and props don't change, changes are only reflected when component re-renders

If you want to log the updated value of clicked, put the log statement in the useEffect hook.

You can't update and log the updated value of any state variable in the same render. Component will have to re-render to reflect changes due to state update.

Similarly, if you want to call a function with the updated value of clicked, call the function from inside the useEffect hook.

about 4 years ago · Juan Pablo Isaza Report

0

setClicked is asynchronous. You must check the state updated in useEffect

function LoginComponent(){
  const [clicked, setClicked] = useState(false)
  
  function handleClick(){
    setClicked(true)
  }

  useEffect(() => {
    console.log(clicked);
  },[clicked])

  return(
    <a onClick={handleClick}>
      random text
      </a>
  )
}
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!