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:
isLoadingScriptstaystrue. Add your own timeout if the widget is optional. - When another component already injected the same
src, the hook reportsfalseat once, even if that script is still loading. - Changing
srcafter mount has no effect. Remount withkey={src}to load another script. - The script is never removed on unmount.