3

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'

Yoel
  • 7,555
  • 6
  • 27
  • 59
rick
  • 554
  • 6
  • 18

2 Answers2

2

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

Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41
1

you need use setState To cause new render

just add

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

then to change it use setAux(1)

Yoel
  • 7,555
  • 6
  • 27
  • 59