Created
November 29, 2018 21:35
-
-
Save sergiodxa/2733d1922853a4c3593e668eb2fc4ceb to your computer and use it in GitHub Desktop.
Hook to use NProgress in a Next.js application
This file contains 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