title: How to use a global variable in several files
body: <p>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.</p>
  <p>global.js:</p>
  <pre><code>export let myGlobal = 0
  </code></pre>
  <p>IncButton.js:</p>
  <pre><code>import { Component } from 'react'
  import { myGlobal } from './global'
  
  class IncButton extends Component {
      render() {
          return (
              &lt;button onClick={() =&gt; { myGlobal = myGlobal + 1 }}&gt;increase&lt;/button&gt;
          )
      }
  }
  
  export default IncButton
  
  window.inc = () =&gt; {
      myGlobal = myGlobal + 1
  }
  </code></pre>
  <p>App.js:</p>
  <pre><code>import { myGlobal } from './global'
  import IncButton from './IncButton'
  
  function App() {
    return (
      &lt;&gt;
        {myGlobal}
        &lt;IncButton /&gt;
      &lt;/&gt;
    );
  }
  export default App;
  </code></pre>
  <p>Pressing <code>IncButton</code> throws <code>ReferenceError: assignment to undeclared variable myGlobal</code>. Calling inc() directly from console throws the same error.</p>
  <p>Using <code>let myGlobal = 0</code> 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 <code>{}</code> should be in the same scope.</p>
  <p>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?</p>
  <p>Note 1: The rest of the code for the example above is just the default from create-react-app.</p>
  <p>Note 2: I do know that using global variables is often not a good idea.</p>