Skip to the content

useScript

useScript injects an external <script async> into <body> once and reports when it has loaded. The script's id is a hash of src, so mounting the hook in several components never injects the same URL twice. Use it for third-party widgets that must load at runtime.
Hooks

Signature

const { isLoadingScript } = useScript({ src: string });
Name
Type
Description
src
string
URL of the script. Read on mount only.
isLoadingScript
boolean
true until the script fires load.
Scrolls sideways inside the table. The page does not.

Example

import { Spinner } from '@apollion-dsi/core/elements/spinner';
import { useScript } from '@apollion-dsi/core/hooks';

function MapWidget() {
  const { isLoadingScript } = useScript({ src: 'https://example.com/widget.js' });

  if (isLoadingScript) return <Spinner label="Loading map" />;
  return <div id="widget" />;
}

Pitfalls

  • A load error is not reported: isLoadingScript stays true. Add your own timeout if the widget is optional.
  • When another component already injected the same src, the hook reports false at once, even if that script is still loading.
  • Changing src after mount has no effect. Remount with key={src} to load another script.
  • The script is never removed on unmount.

See also