A React hook for dynamically loading external scripts and tracking their load state. Current stable version is 1.7.2. The package is actively maintained with regular updates. It provides a simple API: call useScript with a script URL and get loading/error states. Key differentiators: automatic deduplication (multiple components loading the same script share a single request), support for onload callbacks, a checkForExisting flag for environments where the script may already be present, and conditionally loading by setting src to null. Includes TypeScript definitions and supports React 16.8.6 through 18.
npm install react-script-hookVerified import paths — ran on the pinned version, not inferred.
Demonstrates loading the Stripe.js script dynamically using useScript and conditionally rendering a StripeProvider only after the script loads.
If you need to remove the script on unmount, consider manually managing the script element or use a custom cleanup effect.
Only set src to null conditionally if you intend to skip loading initially. Do not toggle src to null to remove a previously loaded script.
Always destructure as an array: const [loading, error] = useScript(...);
Use the checkForExisting option to avoid adding scripts in SSR, or guard with useEffect only on the client.
Ensure correct import: import useScript from 'react-script-hook' (default) or import { useScript } from 'react-script-hook' (named).Pass an object with a src string: useScript({ src: 'https://example.com/script.js' })Only call useScript in client-side code. Use dynamic import or useEffect to conditionally load the hook on the client.