useScript()
The
useScript() hook simplifies loading external JavaScript files dynamically. It handles the creation of the script tag, prevents duplicate loading of the same script, and provides the current loading status (idle, loading, ready, error).Import
typescript
Usage
Click the button to dynamically load jQuery from a CDN.
Script Status:idle
This hook prevents duplicate tags. If you click load again, it uses the cached status instantly.
Component.tsx
API
Arguments
src– string The source URL of the script to load. If an empty string or null is passed, the status remains ‘idle‘.
Returns
Returns a string representing the loading status:
"idle"– Script has not started loading yet (src is empty)."loading"– Script is currently being fetched."ready"– Script has finished loading and is ready to use."error"– Script failed to load.