useScript
Load and manage external JavaScript scripts with useScript.
Install:
npm i @uidotdev/usehooks
Description:
The useScript hook is useful for dynamically loading external JavaScript scripts into a React component. It manages the loading and status of the script, allowing you to conditionally render components or perform actions based on whether the script has been successfully loaded or encountered an error. The hook keeps track of the script’s status, such as “loading,” “ready,” or “error,” and provides this status as a return value. Additionally, it offers options to remove the script when the component is unmounted, ensuring proper cleanup.
Parameters
Name | Type | Description |
---|---|---|
src | string | This is the URL source of the script to be loaded. |
options | object | This is an optional configuration object provided when calling useScript . It currently accepts one property removeOnUnmount which when set to true , will remove the script tag from the document body on component unmount. |
Return Values
Name | Type | Description |
---|---|---|
status | string | This represents the status of the script load. Possible values are: idle , loading , ready , and error . |
Demo:
Example:
import * as React from "react";
import { useScript } from "@uidotdev/usehooks";
import ScriptMeta from './ScriptMeta'
export default function App() {
const status = useScript(
`https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js`,
{
removeOnUnmount: false,
}
);
React.useEffect(() => {
if (typeof window.$$ !== "undefined") {
const id = document.id("moo");
id.setStyle("background-color", "var(--green)");
}
}, [status]);
const isReady = status === "ready";
return (
<section>
<h1>useScript</h1>
<p>
<span id="moo" className={isReady ? "ready" : ""} />
<label>Status: {status}</label>
</p>
{status === "ready" && (
<ScriptMeta title="MooTools" status={status} meta={window.MooTools} />
)}
</section>
);
}