name | rank | tagline | sandboxId | previewHeight | relatedHooks | |
---|---|---|---|---|---|---|
useScript |
14 |
Load and manage external JavaScript scripts with useScript. |
usescript-dux91r |
300px |
|
import CodePreview from "../../components/CodePreview.astro"; import HookDescription from "../../components/HookDescription.astro"; import StaticCodeContainer from "../../components/StaticCodeContainer.astro";
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 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 two optional properties: `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount, and `customAttributes` which is an object of custom string attributes that will be added to the script tag, this can be useful for specifying things like license keys in `data-x` attributes. |
| Name | Type | Description |
| ------ | ------ | ----------- |
| status | string | This represents the status of the script load, `loading`, `ready`, `error`, or `unknown`. An `unknown` script is one that previously exists in the document, but was not added via `useScript`. |
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,
customAttributes: {
"data-uid": "useScript",
},
}
);
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>
);
}