Skip to content

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 ready and error.
  • Is safe to call during SSR (no DOM access on the server).

When src is null, the hook:

  • Does not create or modify any &lt;script&gt; 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 — Sets script.async (default: true).
  • defer — Sets script.defer when provided.

Returns

object

An object describing the current load state:

  • status: One of 'idle' | 'loading' | 'ready' | 'error'.
  • ready: true when status === 'ready'.
  • error: true when status === '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 });

Released under the MIT License.