title: Youtube iFrame API - React, Player is Undefined
body: <p>I am currently using the iFrame API from my project and I am trying to have custom volume controls so that the user is able to change the volume outside of the iframe video. I have set up the player, but it is always undefined when it's being called outside an eventHandler.</p>
  <pre><code>  const { youtubeDetails, volume } = useContext(GlobalContext);
    useYoutube(loadVideo);
  
    let player: any;
    function loadVideo() {
      (window as any).YT.ready(function () {
        player = new window.YT.Player(&quot;player&quot;, {
           events: {
             onStateChange: onStateChange
           }
        });
      });
    }
  
    useEffect(() =&gt; {
      console.log(player)  // never defined
      changeVolume()     
    }, [volume]);
  
   function onStateChange() {
     console.log(player)  // always defined
   }
  
    function changeVolume() {
      player.setVolume(volume * 100);
    }
  </code></pre>
  <p>This is because loadVideo() is never called again after the very first rerender. Is there a work around this structure so that the goal functionality is achieved?</p>
  <p>The custom useYoutube Hooks is as follows:</p>
  <pre><code>import React from &quot;react&quot;;
  
  export const useYoutube = (callback: any) =&gt; {
    React.useEffect(() =&gt; {
      if (!(window as any).YT) {
        var tag = document.createElement(&quot;script&quot;);
        tag.src = &quot;https://www.youtube.com/iframe_api&quot;;
        var firstScriptTag = document.getElementsByTagName(&quot;script&quot;)[0];
        firstScriptTag?.parentNode?.insertBefore(tag, firstScriptTag);
        tag.onload = callback;
      } else {
        callback();
      }
    }, []);
  };
  </code></pre>