External JS in react

External JS can be imported using 4 ways.
  • Install NPM package for JS lib and import it in a component that needs it
  • Using script tag in index.html - not good way because it will load everytime
  • Using react-script-tag package
  • Using react-helmet package
  • Dynamically creating script tag

import { useEffect } from 'react';

const loadScript = url => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};

export default loadScript;

// Now we can use this custom hook in the components that need dynamic script
// Ideally we should check if external JS is available in NPM registry and use that.
import loadScript from 'customHooks/loadScript';

const Component1 = props => {
    loadScript('https://code.jquery.com/jquery-3.6.1.min.js');
}

const Component2 = props => {
    loadScript('https://code.jquery.com/jquery-3.6.1.min.js');
}

Complex problems, Simple Solutions