title: Can I declare Ref at the global scope to manipulate a component from a function outside its scope?
body: <p>I would like to have a custom hook that would provide me with a <code>ScrollView</code> component and a function to imperatively control the scrolling of that given component.</p>
  <p>I'm using a library called <a href="https://github.com/APSL/react-native-keyboard-aware-scroll-view" rel="nofollow noreferrer">react-native-keyboard-aware-scroll-view</a>, which allows me to catch the reference of the component trough a <a href="https://github.com/APSL/react-native-keyboard-aware-scroll-view#props" rel="nofollow noreferrer">prop</a> called <code>innerRef</code>. Through that reference I have access to a series of <a href="https://github.com/APSL/react-native-keyboard-aware-scroll-view#methods" rel="nofollow noreferrer">methods</a> that I can use to manipulate the scrolling.</p>
  <p>The only way that I found for that &quot;control function&quot; to have access to the reference while being outside the scope of the <code>ScrollView</code> component was to create that <code>ref</code> globally using <code>React.createRef</code> like below:</p>
  <pre class="lang-js prettyprint-override"><code>const ref = createRef();
  
  const ScrollView = ({ children, ...props }) =&gt; {
    return (
      &lt;KeyboardAwareScrollView
        {...props}
        innerRef={(inner) =&gt; {
          ref.current = inner; //adding ref to scrollview
        }}
      &gt;
        {children}
      &lt;/KeyboardAwareScrollView&gt;
    );
  };
  
  const useScrollTo = () =&gt; {
  
    const scrollTo = (position) =&gt; {
      if (ref.current &amp;&amp; position) {
  
       /* controlling scroll using ref */
        ref.current.scrollTo({
          x: 0,
          y: position,
          animate: true
        });
      }
    };
  
    return { ScrollView, scrollTo };
  };
  
  export default useScrollTo;
  </code></pre>
  <p>Even though <code>const</code> declarations at the global scope create globals that are not part of the global object it feels anti-pattern to me, so I'd like to know if there's a proper way for me to do this without the need of having a ref in the global scope like this. Is this even possible?</p>
  <h3>Edit</h3>
  <p>Here's an <a href="https://codesandbox.io/s/mystifying-archimedes-xjijjf?from-embed" rel="nofollow noreferrer">example</a> of this hook being used to assist with form validation on a long form, pointing the user to the input that has failed to pass validation:</p>