Created
February 2, 2022 00:48
-
-
Save msankhala/e02ef2d02838dca338a90afbba3221a8 to your computer and use it in GitHub Desktop.
React hook useScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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