Skip to main content

useScript

The useScript hook loads an external script and reports its loading status. The same src is only added to the page once, even if many components use it, and every component is notified when it finishes.

Usage​

Installation​

import { useScript } from "hookstorm";

Parameters​

  • src — The script URL. Pass null to skip loading.
  • options — (optional) An object with:
    • async — Load the script asynchronously. Default: true.
    • removeOnUnmount — Remove the <script> tag when the component unmounts. Default: false.

Return Values​

  • status — One of "idle" (no src), "loading", "ready" or "error".

Example Usage​

import { ReactElement } from "react";
import { useScript } from "hookstorm";

export default function MapView(): ReactElement {
const { status } = useScript("https://maps.example.com/sdk.js");

if (status === "error") return <p>Failed to load the map.</p>;
if (status !== "ready") return <p>Loading map...</p>;

return <div id="map" />;
}

Notes​

  • A script that is already on the page and finished loading is reported as "ready" immediately.
  • Use src = null to load a script conditionally, for example only after the user accepted cookies.
  • Only load scripts from sources you trust — they run with full access to your page.