Created
September 15, 2022 09:18
-
-
Save Akifcan/ec0a6a5d358ef77f57c375cd1ab13de9 to your computer and use it in GitHub Desktop.
Next.js useScript hook. Rerender script when route changed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { ReactNode, useState, useEffect } from "react" | |
import { useRouter } from "next/router" | |
import Script from "next/script" | |
const useScript = (paths: string[]) => { | |
const [scriptTag, setScriptTag] = useState<ReactNode>(<></>) | |
const router = useRouter() | |
useEffect(() => { | |
if (!router.isReady) return | |
router.events.on("routeChangeStart", () => { | |
setScriptTag(<></>) | |
}) | |
setScriptTag(<> | |
{paths.map((x, i) => { | |
return <Script key={i} className='script-tag-js' src={`${x}?v=${Math.random() * 999}`} type='module' /> | |
})} | |
</>) | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [router.asPath, router.isReady]) | |
return { scriptTag } | |
} | |
export default useScript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment