Docs
useScript
Load and manage external JavaScript scripts with useScript.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-script
Usage
"use client"
import * as React from "react"
import { useScript } from "@/hooks/use-script"
import ScriptMeta from "./script-meta"
export function Component() {
const status = useScript(
"https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js",
{
removeOnUnmount: false,
customAttributes: {
"data-uid": "useScript",
},
}
)
React.useEffect(() => {
if (typeof window.$$ !== "undefined") {
const id = document.id("moo")
id.setStyle("background-color", "var(--green)")
}
}, [status])
const isReady = status === "ready"
return (
<section>
<h1>useScript</h1>
<p>
<span id="moo" className={isReady ? "ready" : ""} />
<label>Status: {status}</label>
</p>
{status === "ready" && (
<ScriptMeta title="MooTools" status={status} meta={window.MooTools} />
)}
</section>
)
}
Status Definitions
loading
: Script is currently being loadedready
: Script successfully loadederror
: Failed to load scriptunknown
: Script already existed in DOM before hook initialization
Advanced Usage
Loading Multiple Scripts
const stripeStatus = useScript("https://js.stripe.com/v3/")
const analyticsStatus = useScript("https://analytics.example.com/sdk.js")
Conditional Loading
const needsPayment = useAppSelector((state) => state.checkout.needsPayment)
const status = useScript(needsPayment ? PAYMENT_SCRIPT_URL : "")
Error Handling
const status = useScript("https://third-party-script.com/sdk.js")
useEffect(() => {
if (status === "error") {
showErrorToast("Failed to load required components")
}
}, [status])
Best Practices
- Use
removeOnUnmount: true
for scripts that shouldn't persist between page navigations - Combine with
React.Suspense
for better loading states - Always handle
error
status to prevent UI freezes - Use
unknown
status to detect existing script integrations - Consider adding script integrity hashes through additional HTML attributes
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
src | string | URL source of the script to be loaded | - | No |
options? | object | Optional configuration object | {} | Yes |
options.removeOnUnmount | boolean | When true, removes script tag on component unmount (default: false) | false | Yes |
options.customAttributes | Record<string, string> | customAttributes which is an object of custom string attributes that will be added to the script tag, this can be useful for specifying things like license keys in data-x attributes. | {} | Yes |
Return Values
Name | Type | Description |
---|---|---|
status | ScriptStatus | This represents the status of the script load, loading , ready , error , or unknown . An unknown script is one that previously exists in the document, but was not added via useScript . |