streamich/react-use

Feature request: useScript

Open

#1249 opened on May 29, 2020

View on GitHub
 (4 comments) (8 reactions) (0 assignees)TypeScript (43,979 stars) (3,273 forks)batch import
good first issuehelp wanted🎂 new hook

Description

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.

Contributor guide