1

Suppose I have a state value and it's being rendered as data-value in the DOM.

And the state is being changed by a handleClick function,

const handleClick = (e) => { 
   console.log(e.target) // it shows data-value: !value instead of value
   setValue(!value) 
   console.log(e.target)
}

Inside handleClick function, if I console e.target before changing the state, it shows the next state value even before changing the state.

CodeSandbox: https://codesandbox.io/s/dank-frost-1qku6?file=/src/App.js

Delowar Hosain
  • 2,214
  • 4
  • 18
  • 35
  • sometimes you can't trust console.log https://stackoverflow.com/questions/23392111/console-log-async-or-sync – diedu Jun 25 '21 at 04:32

1 Answers1

0

IMO, this should never happen. You can probably try running the React app again or clear your browser cache. I changed your handleClick to this

  const handleClick = (e) => {
    console.log('Before calling setValue: ',e.target.dataset["value"], e.target); 
    setValue(!value);
    console.log('After calling setValue: ',e.target.dataset["value"], e.target);
}

Both logs the correct value of value on my console, ie, I see the previous state and not the updated state. So I get the expected behaviorur. setValue is asynchronous and the updated value should only be readable inside a useEffect that takes value as a dependency.

useEffect(()=>{
  console.log('Updated Value: ',value) 
},[value])

Anywhere inside handleClick the updated state will not be readable.

Siddhant Varma
  • 574
  • 5
  • 10