Skip to content

Instantly share code, notes, and snippets.

@msankhala
Created February 2, 2022 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msankhala/e02ef2d02838dca338a90afbba3221a8 to your computer and use it in GitHub Desktop.
Save msankhala/e02ef2d02838dca338a90afbba3221a8 to your computer and use it in GitHub Desktop.
React hook useScript
// hooks/useScript.js
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment