I was trying to use a global variable in a React app for debugging purposes, and ran into some issues that made me realize that I don't understand how global variables in javascript works.
global.js:
export let myGlobal = 0
IncButton.js:
import { Component } from 'react'
import { myGlobal } from './global'
class IncButton extends Component {
render() {
return (
<button onClick={() => { myGlobal = myGlobal + 1 }}>increase</button>
)
}
}
export default IncButton
window.inc = () => {
myGlobal = myGlobal + 1
}
App.js:
import { myGlobal } from './global'
import IncButton from './IncButton'
function App() {
return (
<>
{myGlobal}
<IncButton />
</>
);
}
export default App;
Pressing IncButton
throws ReferenceError: assignment to undeclared variable myGlobal
. Calling inc() directly from console throws the same error.
Using let myGlobal = 0
at top of IncButton.js, and removing import removes errors, but of course this makes App.js not see the same myGlobal. My thinking is that imported variables and variables outside any function or {}
should be in the same scope.
So I would like to know: Why is the above not working, what is the right way to share a global variable across files, and do React add any further complications to this?
Note 1: The rest of the code for the example above is just the default from create-react-app.
Note 2: I do know that using global variables is often not a good idea.