useScript
function useScript(src: string | null): ScriptStatus;
type ScriptStatus = "idle" | "loading" | "ready" | "error";
Loads a third-party script, such as a maps, payments or chat widget, and tells you when it is ready to use.
- Each
srcgets one async<script>tag, shared by every component that asks for it, so rendering ten maps loads the library once. - A
<script>the page already has forsrc, for example in its HTML, counts as"ready". - Pass
nullto load nothing yet ("idle"), for example until the user opens the widget. - The tag stays when components unmount: removing it wouldn't unload the code. A script that failed stays failed until the page reloads.
- During server rendering it is
"loading"(or"idle"fornull).
Example
import { useScript } from "react-honey-hooks";
function Map({ center }: { center: LatLng }) {
const status = useScript("https://maps.example.com/sdk.js");
if (status === "error") return <p>The map couldn't load.</p>;
if (status !== "ready") return <p>Loading map…</p>;
return <MapView center={center} />;
}