useScript
A hook to load external scripts dynamically.
Overview
useScript simplifies loading external scripts (like Google Analytics, Stripe, or visualization libraries). It handles loading states, error handling, and prevents duplicate script injection.
Demo
API Reference
function useScript(src: string): ScriptStatusType ScriptStatus = 'idle' | 'loading' | 'ready' | 'error'
Parameters
| Name | Type | Description |
|---|---|---|
src | string | The source URL of the script to load. |
Usage Example
import { useScript } from 'react-hooks-ts'
function StripeComponent() {
const status = useScript('https://js.stripe.com/v3/')
if (status === 'loading') return <div>Loading Stripe...</div>
if (status === 'error') return <div>Failed to load Stripe</div>
return <div>Stripe is ready!</div>
}