useScript

Dynamically load an external script.

https://www.shaktools.com/shak-hooks
Utility

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useScript } from "@shak-hooks/usehooks";
Source: packages/react/src/useScript.ts

Signature

signature.ts
export function useScript(src: string, options: UseScriptOptions = {}): ScriptStatus

Parameters

NameTypeOptionalDefault
srcstringNo-
optionsUseScriptOptionsYes{}

Returns

ScriptStatus

Exported Types

types.ts
1export type ScriptStatus = 'idle' | 'loading' | 'ready' | 'error';
2
3export interface UseScriptOptions {
4 removeOnUnmount?: boolean;
5}

Implementation

use-script.ts
1import { useState, useEffect } from "react";
2
3export type Status = "idle" | "loading" | "ready" | "error";
4
5export function useScript(src: string): Status {
6 const [status, setStatus] = useState<Status>(src ? "loading" : "idle");
7
8 useEffect(() => {
9 if (!src) {
10 setStatus("idle");
11 return;
12 }
13
14 let script: HTMLScriptElement | null = document.querySelector(`script[src="${src}"]`);
15
16 if (!script) {
17 script = document.createElement("script");
18 script.src = src;
19 script.async = true;
20 script.setAttribute("data-status", "loading");
21 document.body.appendChild(script);
22
23 const setAttributeFromEvent = (event: Event) => {
24 script?.setAttribute(
25 "data-status",
26 event.type === "load" ? "ready" : "error"
27 );
28 };
29
30 script.addEventListener("load", setAttributeFromEvent);
31 script.addEventListener("error", setAttributeFromEvent);
32 } else {
33 setStatus(script.getAttribute("data-status") as Status);
34 }
35
36 const setStateFromEvent = (event: Event) => {
37 setStatus(event.type === "load" ? "ready" : "error");
38 };
39
40 script.addEventListener("load", setStateFromEvent);
41 script.addEventListener("error", setStateFromEvent);
42
43 return () => {
44 if (script) {
45 script.removeEventListener("load", setStateFromEvent);
46 script.removeEventListener("error", setStateFromEvent);
47 }
48 };
49 }, [src]);
50
51 return status;
52}

Advertisement

Google Ads

Usage

example.tsx
1import { useScript } from "@shak-hooks/usehooks";
2
3const result = useScript("...", undefined);
4// result: ScriptStatus
5// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy