1

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?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Anderson Laverde
  • 316
  • 1
  • 4
  • 15

2 Answers2

1

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.

Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

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])
Tony Nguyen
  • 3,298
  • 11
  • 19