0

Apparently if you need a state for a component you should define variables with useState. But in the example below I have a simple button that increments a variable declared normally, and every time it gets clicked the logged variable is actually incremented as if there is a "state".

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


const App: () => Node = () => {
  
  var a = 0;
  return (
    <>
      <Button 
        title='click me'
        onPress={() => {
          a++;
          console.log(a)
        }}/>
    </>
  );
};

export default App;
 LOG  1
 LOG  2
 LOG  3
 LOG  4
 LOG  5
 LOG  6
 ...

Since App is a function and not a class why the variable a is still defined after the return statement? Should't it be out of scope? (I do understand that every time the components renders var a restarts from zero, and thats's why you should use useState and setState if you want to display it, but why does it keep a state until the next render?)

0 Answers0