HooksuseScript

useScript()

The useScript() hook simplifies loading external JavaScript files dynamically. It handles the creation of the script tag, prevents duplicate loading of the same script, and provides the current loading status (idle, loading, ready, error).

Import

typescript
import { useScript } from 'the-react-hooks';

Usage

Click the button to dynamically load jQuery from a CDN.

Script Status:idle

This hook prevents duplicate tags. If you click load again, it uses the cached status instantly.

Component.tsx
import { useScript } from 'the-react-hooks';

export const Component = () => {
  const status = useScript('https://example.com/some-library.js');

  if (status === 'loading') return <div>Loading library...</div>;
  if (status === 'error') return <div>Error loading script</div>;

  return (
    <div>
      Script is ready! You can now use the global object.
    </div>
  );
}

API

Arguments

  • src string The source URL of the script to load. If an empty string or null is passed, the status remains ‘idle‘.

Returns

Returns a string representing the loading status:
  • "idle" – Script has not started loading yet (src is empty).
  • "loading" – Script is currently being fetched.
  • "ready" – Script has finished loading and is ready to use.
  • "error" – Script failed to load.