# useScript

Loads an external script once and reports its status: `'idle'`, `'loading'`, `'ready'`, or `'error'`.

Every component using the same `src` shares one `<script>` tag and one status. The tag is added on mount (never on the server) and is not removed on unmount, because a script that has run cannot be unloaded. Status is `'idle'` on the server, during hydration, and while disabled.

## Import

```ts
import { useScript } from '@vincent.ri/react-tils'
// or only this hook
import { useScript } from '@vincent.ri/react-tils/useScript'
```

## Usage

```ts
const status = useScript('https://js.stripe.com/v3/', { attributes: { nonce } })
if (status === 'error') return <p>Payments are unavailable right now.</p>
if (status !== 'ready') return <Spinner />
return <Checkout stripe={window.Stripe(publishableKey)} />
```

## When to use it

A third-party SDK has no npm package or must load from its own domain, e.g. Stripe.js, Google Maps, or a chat widget.

## When not to

An npm package exists; import it, and use `import()` to load it lazily. In Next.js, `next/script` also handles loading strategies. A failed load stays `'error'` for that `src`; to retry, change the `src`.

## API

```ts
function useScript(src: string, options?: ScriptOptions): ScriptStatus
```

| Parameter | Description |
| --- | --- |
| `src` | Script URL. |
| `options` | `enabled` and `attributes`. Optional. |

### Types

```ts
export type ScriptStatus = "idle" | "loading" | "ready" | "error";
export type ScriptOptions = {
  /** Load only while `true`, e.g. after consent or when a feature opens. Default `true`. */
  enabled?: boolean;
  /** Extra attributes for the `<script>` tag, e.g. `{ nonce, crossorigin: 'anonymous' }`. Applied when it is created. */
  attributes?: Record<string, string>;
};
```

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useExternal`.

---

437 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useScript.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useScript/
Previous: [useEventSource](https://vincentri.github.io/react-tils/hooks/useEventSource.md)
Next: [useServiceWorkerUpdate](https://vincentri.github.io/react-tils/hooks/useServiceWorkerUpdate.md)
