React: can't understand how useState works

Hi,

Can someone please help me understand what is happening in the below code. I went through React documentation but it didn’t clarify everything I wanted.

I’m building a calculator and have created the below functional component.

  1. I have an onClick event handler which triggers handleDigit function when a user clicks on a digit.
  2. Then the function updates the currentValue (initial value: 0) using setCurrentValue.

My question is why when I click on any digit, it first returns the initial value and then the proper number? I Was thinking that if I use setCurrentValue(digit) and then console.log(currentValue), it would log already an updated value of the current digit but instead with every click it first returns the previous value, starting from the initial one.

Can someone please tell me what I am missing here?

export default function Layout() {

    const [currentValue, setCurrentValue] = useState(0);

const handleDigit = (digit) => {

   setCurrentValue(digit);
   console.log(currentValue);  // returns 0, 
     
}

Thank you

to see updated currentValue use useEffect hook

  useEffect(() => {
  console.log(currentValue)
  }, [currentValue])
1 Like

I think the console.log() is triggered before the state changed

thank you, do you mean that this is kind of a performance issue?

No it’s how javascript works.
Search for hoisting in javascript for better understanding

2 Likes

I more or less understand the idea of moving declarations to the top but I still don’t understand why in this case when I’m calling two functions their order would be moved around. In the handleDigit functions I first call setCurrentValue then console.log so they must have been swapped then? It doesn’t make sense to me. Or did I misunderstand something?

I know it’s little bit tricky, check these

setState with console

setState hook

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.