Packages
react
hooks
useLoadScript

useLoadScript

The useLoadScript hook loads an external script tag in the browser. It allows React components to lazy-load large third-party dependencies.

Props

NameTypeDescriptionInfo
urlstringThe URL of the script to load.
optionsobject (optional)Additional options for loading the script.
options.moduleboolean (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

ValueDescription
'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;