Feature request: useScript
Is your feature request related to a problem? Please describe.
Problem: I'd like to dynamically import scripts as <script> tags.
Describe the solution you'd like Proposal:
const useScript = ({ url, id, type = 'text/javascript', async = true }) => {
const [ready, setReady] = React.useState(false);
const [failed, setFailed] = React.useState(false);
React.useEffect(() => {
if (document.getElementById(id)) {
return;
}
const element = document.createElement('script');
element.src = url;
element.type = type;
element.async = async;
element.id = id;
setReady(false);
setFailed(false);
element.onload = () => setReady(true);
element.onerror = () => {
setReady(false);
setFailed(true);
};
document.head.appendChild(element);
return () => {
document.head.removeChild(element);
};
}, [url, id]);
return { ready, failed };
};
Describe alternatives you've considered I'm using this the code above directly in my project.
Maybe also on top of that we could build a makeScript helper that defines script at module scope.
const useMyScript = makeScript({ url, id, type, async });
useMyScript.preload();
const Demo = () => {
const { data, error, isLoading } = useMyScript();
};
.preload() could initiate loading already at module scope.
I will do it ~
For someone who need this feature right now. https://usehooks.com/useScript/
Maybe also on top of that we could build a
makeScripthelper that defines script at module scope.const useMyScript = makeScript({ url, id, type, async });
useMyScript.preload();
const Demo = () => { const { data, error, isLoading } = useMyScript(); };
.preload()could initiate loading already at module scope.
https://github.com/streamich/react-use/pull/1444
Could you merge this? Other hook libraries already support this function.