Search code examples
reactjsreact-nativereact-hooksexposetstate

setState not setting the value correctly in react native (expo)


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>

Solution

  • 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>