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 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

NameTypeDescription
srcstringThis is the URL source of the script to be loaded.
optionsobjectThis 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

NameTypeDescription
statusstringThis 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.

Demo:

Example:

More Hooks:

Sort: