How to change variable with react-native onPress

Viewed 737

I am training in react-native, but I have some comprehension problems.

Why can change the "modalVisible" variable, but I cannot change "aux".

const App = () => {  

  const [modalVisible, setModalVisible] = useState(0);    
  var aux = 0;    
  const _onPress  = (code) => {
    aux = 1
    setModalVisible(code)
  };
  return (
    <SafeAreaView style = {styles.centeredView}>
        <View style = {styles.box}>
        <Pressable
            onPress = {() => _onPress(modalVisible+1)} 
            style={styles.pressable}
          > 
            <Text style = {{color:'black'}}>{modalVisible} {aux}</Text>
          </Pressable></View> 
      </View>
    </SafeAreaView>
  );
};

I deleted some views, so it's not ready for a 'crtl + c' 'crtl + v'

2 Answers

When you change the state of variable using useState hooks, the re rendering of the component take place and the new updated value is shown.

In case of regular variable, aux in this example, even though the value is changed, the re rendering does not occur and the new updated value is not shown.

There is a similar questions here: useState hooks and regular variable

you need use setState To cause new render

just add

const [aux, setAux] = useState(0);

then to change it use setAux(1)

Related