title: Accessing functional component's methods from the 'outside'
body: <p>Let's say that I want to control the loading state of my app by calling the method from outside of the app like so:</p>
  <pre class="lang-js prettyprint-override"><code>setLoading(true)
  </code></pre>
  <p>I have implemented a functional component for which something like that works:</p>
  <pre class="lang-js prettyprint-override"><code>import React from 'react';
  
  function App() {
    const [loading, setLoading] = React.useState(true);
    window.setLoading = (isLoading) =&gt; { setLoading(isLoading) };
  
    if (loading) return 'Loading...';
  
    return 'App content';
  }
  </code></pre>
  <p>I believe however that mapping  the  <code>setLoading()</code> to <code>window</code> is not the best approach. Is it possible then to do it differently?</p>
  <p>If I had a class component, it would look like this:</p>
  <pre class="lang-js prettyprint-override"><code>import React from 'react';
  
  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        loading: true,
      }
    }
  
    setLoading = (loading) =&gt; {
      this.setState({ loading });
    }
  
    render() {
      return(this.state.loading ? 'Loading...' : 'App content');
    }
  }
  </code></pre>
  <p>Then upon rendering I would use callback ref to make the whole component with all it's methods available.</p>
  <pre><code>&lt;App ref={(app) =&gt; { window.app = app }} /&gt;
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>app.setLoading(true)
  </code></pre>
  <p>This approach also pollutes the global scope but it's more concise - the component is exposed as a whole.</p>
  <p>As neither of the approaches is optimal, which one should I use? Is there maybe something better?</p>