MENU
useScript
To dynamically load a JS script:
These are two separate files of a bundler-based project (a hooks/useScript.js module and a consumer that imports it), shown here to illustrate the pattern rather than as a single runnable page.
import { useEffect } from 'react';const useScript = 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 useScript;import useScript from 'hooks/useScript';const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}