Skip to content

Instantly share code, notes, and snippets.

@Akifcan
Created September 15, 2022 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akifcan/ec0a6a5d358ef77f57c375cd1ab13de9 to your computer and use it in GitHub Desktop.
Save Akifcan/ec0a6a5d358ef77f57c375cd1ab13de9 to your computer and use it in GitHub Desktop.
Next.js useScript hook. Rerender script when route changed
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