Global Variables
Global Variables
Global variables in React persist even after re-render. Only the local variable that's instantiated within the React component will not survive the re-rendering, meaning that if the component is updated, those local variable's value will be reset to whatever their default value will be.
let counter = 0;
export default function MainPage() {
let [state, setState] = useState(0);
let localVariable = 0;
function increment() {
counter++;
localVariable++;
console.log(counter);
}
function incrementState() {
localVariable++;
setState(state + 1);
}
return (
<>
<p>The global variable is {counter}</p>
<p>The local variable is {localVariable}</p>
<p>The state variable is {state}</p>
<button onClick={increment}>Increment a global variable</button>
<button onClick={incrementState}>Increment a state variable</button>
</>
)
}
No matter where you try to increment the localVariable it will always be reset back to the initial value that it was assigned which is 0.