useLoadScript
The useLoadScript hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.
Props
| Name | Type | Description | Info |
|---|---|---|---|
url | string | The URL of the script to load. | |
options | object (optional) | Additional options for loading the script. | |
options.module | boolean (optional) | Set to true if the script is a module. | |
options.in | `'head' | 'body'` (optional) | Specify where to inject the script tag. Default is 'body'. |
Returns
ScriptState: The state of the script loading process. Possible values are 'loading', 'done', or 'error'.
ScriptState
| Value | Description |
|---|---|
| 'loading' | The script is currently being loaded. |
| 'done' | The script has been successfully loaded. |
| 'error' | An error occurred while loading the script. |
Example Usage
import React from "react";
import { useLoadScript } from "./useLoadScript";
const MyComponent = () => {
const scriptStatus = useLoadScript("https://example.com/script.js");
return (
<div>
{scriptStatus === "loading" && <p>Loading script...</p>}
{scriptStatus === "done" && <p>Script loaded successfully!</p>}
{scriptStatus === "error" && <p>Error loading script.</p>}
</div>
);
};
export default MyComponent;