Skip to content

Instantly share code, notes, and snippets.

@saitergun
Created July 30, 2023 18:42
Show Gist options
  • Save saitergun/8d9baa1244b264a8932ea51b3f4571c8 to your computer and use it in GitHub Desktop.
Save saitergun/8d9baa1244b264a8932ea51b3f4571c8 to your computer and use it in GitHub Desktop.
NProgress provider component for Next.js app routing
'use client'
import { usePathname } from 'next/navigation'
import { useEffect, useRef } from 'react'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
type Props = {
children: React.ReactNode
}
NProgress.configure({
showSpinner: false,
trickle: true,
trickleSpeed: 200,
minimum: 0.08,
speed: 200,
easing: 'ease',
})
export default function NProgressProvider({ children }: Props) {
const timeOutRef = useRef<NodeJS.Timeout>()
const pathname = usePathname()
useEffect(() => {
if (timeOutRef.current) {
clearTimeout(timeOutRef.current)
NProgress.done()
}
const handleClickWindow = (e: MouseEvent) => {
const el = e.target as HTMLElement
if (el.nodeName === 'A') {
const href = el.getAttribute('href') as string
let nextUrl = new URL(href, window.location.origin)
if (pathname !== nextUrl.pathname) {
timeOutRef.current = setTimeout(() => {
NProgress.start()
}, 300)
}
}
}
window.addEventListener('click', handleClickWindow)
return () => {
window.removeEventListener('click', handleClickWindow)
}
}, [pathname])
return <>{children}</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment