Skip to content

Instantly share code, notes, and snippets.

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