React hook to load a script.
Add the hook via the CLI:
npx @novajslabs/cli add useScript
Or copy and paste the code into your project:
import { useEffect, useState } from 'react'
export const useScript = (url: string) => {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const script = document.createElement('script')
script.src = url
script.async = true
script.onload = () => {
setLoading(false)
}
script.onerror = () => {
setError(`Failed to load script ${url}`)
setLoading(false)
}
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [url])
return { loading, error }
}
React 16.8 or higher
- Name
url
- Type
- string
- Required
- required
- Description
The URL of the script to load.
- Name
loading
- Type
- boolean
- Description
Indicates whether the script is currently being loaded (true) or not(false).
- Name
error
- Type
- string | null
- Description
Error message if the script fails to load, otherwise null.
import { useScript } from './hooks/useScript'
const App = () => {
const { loading, error } = useScript('https://cdn.tailwindcss.com')
if (loading) return <div>Loading Tailwind CSS...</div>
if (error) return <div>Error loading Tailwind CSS: {error}</div>
return <div>Tailwind CSS loaded successfully!</div>
}
export default App
Here are some use cases where this React hook is useful:
- Loading live chat services
- Embedding map services
- Dynamic loading of social media widgets