useScript
Dynamically loads an external <script> tag, deduplicating across components and tracking its status.
Loading preview...
The useScript hook injects an external <script> tag into document.body (or attaches to an existing tag with the same src), deduplicates concurrent requests across multiple mounted components, and returns the current loading status ('idle', 'loading', 'ready', or 'error').
Installation
Usage
Examples
Rendering a Widget Once the Script is 'ready'
Check status === "ready" before initializing or rendering components that depend on the global script.
Conditional Loading and Cleanup on Unmount
Pass null (or shouldPreventLoad: true) to defer loading until needed, and removeOnUnmount: true to remove the <script> tag when the last consumer unmounts.
API Reference
UseScriptOptions
Configuration options for script attributes, conditional loading, and unmount cleanup.
Property
Specification
shouldPreventLoad?uniondefault:false
Prevent the script from loading while
trueFull Signature
removeOnUnmount?uniondefault:false
Remove the
<script> element when the last consumer unmountsFull Signature
id?string
Optional
id attribute for the <script> tag.Full Signature
async?uniondefault:true
Set the
async attribute on the <script> tagFull Signature
defer?uniondefault:false
Set the
defer attribute on the <script> tagFull Signature
crossOrigin?union
CORS setting for the
<script> element.Full Signature
integrity?string
Subresource Integrity (
integrity) hash.Full Signature
type?string
Script
type attribute (e.g. 'module').Full Signature
noModule?union
Set the
noModule attribute on the <script> tag.Full Signature
referrerPolicy?union
Referrer policy for fetching the script.
Full Signature