I am new to React and JS. So the scenario is as follows. I have a function Component like below.
const testComponent = () =>{
const [myState, setMyState] = useState('INITIAL_VALUE')
const updateState = async () => {
setMyState("UPDATED_VALUE")
console.log('updated using hook')
console.log(myState)
}
useEffect(() => {
updateState().then(
() => console.log(myState)
)
})
return(
<div>
<h1>
{myState}
</h1>
</div>
)
}
All the console.log above logs "INITIAL_VALUE", although they all are called after updating the state variable! I was expecting it to be "UPDATED_VALUE" as it is rendered in HTML dom! Why do I still get the old value?
Shouldn't it be logging updated value, since it is executed after a promise inside .then() method? As far as I have understood it is .then() methods are executed once the promise is resolved. But this looks pretty strange! Correct me If am wrong!
When updateState()
resolves, the myState
variable is updated.
But it's new value will only be displayed/logged on next render.