Home > other >  React Native: why do variables declared inside App() get constantly reset, but not those declared ou
React Native: why do variables declared inside App() get constantly reset, but not those declared ou

Time:10-26

The variable declared above the App() function updates as expected when the button is pressed, whereas the one declared within it oscillates statically between two values. Why is this so? Is it because App() is being constantly re-run for every button press?

import { Text, Button, View } from 'react-native';

let globalVar = 10;

export default function App() {
  let localVar = 10;
  const [thing, setThing] = useState(0);
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>{thing}</Text>
      <Button
        title="press"
        onPress={() => setThing((globalVar  = 10))}></Button>
      <Button title="press" onPress={() => setThing((localVar  = 10))}></Button>
    </View>
  );
}

CodePudding user response:

With functional components, everything inside the function and outside the return and hooks goes into the mounting step. Every time we update something in our layout, we go back to the mounting step, so some variables are re-declared. This is easily circumvented using hooks.

Explaining step by step:

  1. On the first click, it updated the value shown in the layout, and then we had the mounting step again, so the variable was declared again.
  2. On the second click, the value shown on the screen remains 20, react used the diff algorithm and saw that there were no changes in the layout, so it did not enter the mounting step.
  3. When you click for the third time, the value of the local var will be at 30, when we set this on the screen, react saw that there was a change in the layout and will re-declare all variables again.
  • Related