I am setting a value to useState hook on a button press but not working.
const [text, setText] = useState("")
const demo = () => {
setText("Hello world")
alert(text)
}
<TouchableOpacity onPress={demo}>
<Text>set Value</Text
</TouchableOpacity>
setText
is async function.
If you alert(text)
old value will be alerted.
You should useEffect
const [text, setText] = useState("")
const demo = () => {
setText("Hello world")
}
useEffect(() => {
alert(text)
}, [text])
<TouchableOpacity onPress={demo}>
<Text>set Value</Text
</TouchableOpacity>