How to inject a Javascript lib within a React project (Spotify Playback SDK)

Hey guys, in this straightforward article I will teach you how we can load a lib Javascript inside a project React. In my case, I needed to do this, because my side project uses Spotify SDK but, Spotify Playback SDK hasn't an npm package.

Use useEffect hook

useEffect(() => {
    // Inject the script in the project
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.onload = function() {
        initializePlayer();
    }
    script.src = 'https://sdk.scdn.co/spotify-player.js';
    head.appendChild(script);
}, []);

function initializePlayer() {
    console.log('Script was loaded');
}

Note that our code will be execute once and when onload is ready, call the function. Using useEffect with [] our code React will to execute only once.