React Native : make useState update on real time

I have this code on react native where I increment a counter by 1 after each button press

     function App() {
          const [counter,setCounter]=useState(0);
          return (
            <View>
              <Button title="hello" onPress={()=> 
              {setCounter(counter+1);console.log("display 
               counter in console" ,counter)}}>
                </Button>

              {counter%2==1 ? <Text> display counter in UI</Text> 
               : null }
    
               <View>
               <Text> thank you for clicking the button </Text>
               </View>
        
            </View>
           )
             }

After the first click the counter is equal to 0 and the console shows 0 instead of 1 so the JSX component won’t show.
I know that useState is asynchronous but how to solve it if showing a JSX is depending on updating the state on real time.

UPDATE: It seems that the JSX displays when excpected but I’m wondering why console.log will not update on real time ? I mean why console.log shows 0 when it is supposed to show 1

You just need to add pre-increment operator on setCounter state. and Change const to var in useState declaration.

https://snack.expo.dev/j70TThHHb

export default function App() {
              var [counter,setCounter]=useState(0);
              return (
                <View style={{marginTop:25}}>
                  <Button title="hello" onPress={()=> 
                  {setCounter(++counter);
                  console.log("display  counter in console" ,counter)}}>
                    </Button>
    
                  {counter%2==1 ? <Text> display counter in UI</Text> 
                   : null }
        
                   <View>
                   <Text> thank you for clicking the button </Text>
                   </View>
            
                </View>
               )
                 }

useState hook is asynchronous, so you can not access it’s new values immediately
And there is no callback for it (unlike setState)
But if you want to listen to it’s changes, you can use useEffect hook like this

useEffect(() => {
    console.log('display  counter in console', counter);
}, [counter]);

Leave a Comment