-
-
Save HeathHopkins/881bf1ed9598b8d716073c2f77857386 to your computer and use it in GitHub Desktop.
Hook to use NProgress in a Next.js application
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 { useRef, useEffect } from "react"; | |
import NProgress from "nprogress"; | |
import Router from "next/router"; | |
function useNProgress(showAfterMs = 300, options = {}) { | |
const timer = useRef(null); | |
function routeChangeStart() { | |
const { showAfterMs } = this.props; | |
clearTimeout(timer.current); | |
timer.current = setTimeout(NProgress.start, showAfterMs); | |
} | |
function routeChangeEnd() { | |
clearTimeout(timer.current); | |
NProgress.done(); | |
} | |
useEffect(() => { | |
if (options) { | |
NProgress.configure(options); | |
} | |
Router.events.on("routeChangeStart", this.routeChangeStart); | |
Router.events.on("routeChangeComplete", this.routeChangeEnd); | |
Router.events.on("routeChangeError", this.routeChangeEnd); | |
return () => { | |
Router.events.off("routeChangeStart", this.routeChangeStart); | |
Router.events.off("routeChangeComplete", this.routeChangeEnd); | |
Router.events.off("routeChangeError", this.routeChangeEnd); | |
} | |
}, [showAfterMs, options]); | |
} | |
export default useNProgess; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment