useExternalScript
The useExternalScript
hook allows you to dynamically load an external script in your React component.
Add the utility
npx @ivnatsr/ezreact add use-external-script
import { useState, useEffect } from 'react'
export function useExternalScript(src) { const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [retryValue, setRetryValue] = useState(Math.random())
const retryScriptLoad = () => { setRetryValue(Math.random()) }
useEffect(() => { retryValue
setLoading(true) setError(false)
const script = document.createElement('script') script.setAttribute('src', src) script.setAttribute('async', 'true') document.body.appendChild(script)
const onLoad = () => { setLoading(false) setError(false) }
const onError = () => { setLoading(false) setError(true) }
script.addEventListener('load', onLoad) script.addEventListener('error', onError)
return () => { script.removeEventListener('load', onLoad) script.removeEventListener('error', onError) document.body.removeChild(script) } }, [src, retryValue])
return { loading, error, retryScriptLoad }}
import { useState, useEffect } from 'react'
export function useExternalScript(src: string) { const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [retryValue, setRetryValue] = useState(Math.random())
const retryScriptLoad = () => { setRetryValue(Math.random()) }
useEffect(() => { retryValue
setLoading(true) setError(false)
const script = document.createElement('script') script.setAttribute('src', src) script.setAttribute('async', 'true') document.body.appendChild(script)
const onLoad = () => { setLoading(false) setError(false) }
const onError = () => { setLoading(false) setError(true) }
script.addEventListener('load', onLoad) script.addEventListener('error', onError)
return () => { script.removeEventListener('load', onLoad) script.removeEventListener('error', onError) document.body.removeChild(script) } }, [src, retryValue])
return { loading, error, retryScriptLoad }}
Return
This hook returns an object containing the following properties:
loading
: A boolean indicating whether the script is currently loading.error
: A boolean indicating whether there was an error loading the script.retryScriptLoad
: A function that can be called to retry loading the script.
Parameters
src
: A string representing the URL of the external script to load.
Example
import { useExternalScript } from './path/to/use-external-script'
const ExternalScriptExample = () => { const { loading, error, retryScriptLoad } = useExternalScript('https://example.com/external-script.js')
if (loading) return <p>Loading script...</p>
if (error) { return ( <div> <p>Error loading script</p> <button onClick={retryScriptLoad}>Retry</button> <div> ) }
return <p>Script loaded successfully</p>}
export default ExternalScriptExample