useScript()
useScript(
src,options?):object
Defined in: hooks/dom/useScript.ts:142
React hook to dynamically load an external <script> tag and track its status.
It:
- Reuses an existing
<script src="...">element if one is already present. - Tracks a ScriptStatus value:
'idle' | 'loading' | 'ready' | 'error'. - Exposes convenience booleans
readyanderror. - Is safe to call during SSR (no DOM access on the server).
When src is null, the hook:
- Does not create or modify any
<script>element. - Always reports an effective status of
'idle'.
Parameters
src
URL of the script to load. Use null to disable the hook.
string | null
options?
UseScriptOptions = {}
Optional script tag attributes:
async— Setsscript.async(default:true).defer— Setsscript.deferwhen provided.
Returns
object
An object describing the current load state:
status: One of'idle' | 'loading' | 'ready' | 'error'.ready:truewhenstatus === 'ready'.error:truewhenstatus === 'error'.
status
status:
ScriptStatus
ready
ready:
boolean
error
error:
boolean
Examples
tsx
const { status, ready, error } = useScript('https://example.com/sdk.js');
if (error) {
return <p>Failed to load SDK.</p>;
}
if (!ready) {
return <p>Loading SDK…</p>;
}
return <RealComponentUsingSDK />;tsx
const enabled = useFeatureFlag('third-party-sdk');
const src = enabled ? 'https://example.com/sdk.js' : null;
const { ready } = useScript(src, { async: true, defer: true });