Anderson Laverde
Anderson Laverde

Reputation: 395

How to change useState variable in the same function

I have this variable:

const [userName, setUserName] = useState<string>("initialValue");

With a button click I execute this function:

const FacebookSign = () => {
    console.log(userName);
    setUserName("value2");
    console.log(userName);
}

The userName variable doesn't change and my output is:

initialValue
initialValue

But if I hit the button the second time, I got the output:

value2
value2

Why doesn't the value change the first time?

Upvotes: 1

Views: 948

Answers (2)

Tony Nguyen
Tony Nguyen

Reputation: 3488

When you call setSate, the state is not updated immediately. The state will be updated after a re-render. You can use useEffect to check the most updated state.

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

Upvotes: 1

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

If you read about how the state change mechanism works. The process is asynchronous in nature. So may or may not change immediately. Read more about it here Is useState synchronous?

Also you can use useEffect() hook to see the state change immediately.

Upvotes: 1

Related Questions