0

useState updates immediately inside html codes but in functions will only update on next render?

import { useState } from 'react'

function weird() {

const [data, setData] = useState('previous')

function submit(e) {    <---- when I fired the submit event Form once
    setData('updated')   
    console.log(data)   <---- this will log "previous" value
}
return (
    <from onSubmit={(e)=> submit(e)}>
        {data ? console.log(data) : ''}   <---- but this will log "updated" value
    </from>
)

} export default weird

kal_stackO
  • 11
  • 4

2 Answers2

0

This is due to the fact that setData is an async operation.

Thus, in your function when console.log(data) runs, the setData has not yet been completed and it prints the old value.

While JSX (HTML part) re-renders when the value updates and shows you the updated value instantly.

Yatin Gupta
  • 653
  • 5
  • 12
0

React setState is asynchronous, and will not be reflected immediately. Try using the useEffect hook. https://reactjs.org/docs/hooks-effect.html

Hetarth7
  • 51
  • 7
  • I am aware that useState is asynchronous so I am confused to why 'console.log' inside jsx(html) can read the updated value right away? – kal_stackO Jan 09 '23 at 05:15
  • setState is async that means it lets your further code, while the value updating happens on the background. So you're getting previous value. But after setState is complete and you re-render, the update will be visible. But, console.log works because it is not trying to change the value of any const variable unlike setState, it simply logs the current value to the terminal – Hetarth7 Jan 09 '23 at 13:23