How to Add a Progress Bar on Page Load to Next.js
A very popular module for adding progress bars to JavaScript applications is NProgress
.
We can easily add a progress bar on page loads by adding listeners to Next’s router routeChangeStart
and routeChangeComplete
events.
First off, we have to install this package.
npm install --save nprogress
Then, we can use nprogress
and attach it to our router events.
// _app.jsx
import NProgress from "nprogress";
import { useEffect } from "react";
import Router from "next/router";
const App = ({ Component, pageProps }) => {
useEffect(() => {
Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => NProgress.done());
Router.events.on("routeChangeError", () => NProgress.done());
}, []);
return <Component {...pageProps} />;
};
But we don’t always want the progress bar to show up. It might get annoying for users, especially for pages rendered on the client-side.
We can delay the progress bar and only show it when the page load takes longer than half a second (500ms
).
This can be done using setTimeout()
and clearTimeout()
.
// _app.jsx
import NProgress from "nprogress";
import { useEffect } from "react";
import Router from "next/router";
const App = ({ Component, pageProps }) => {
useEffect(() => {
const delay = 500; // in milliseconds
let timer;
const load = () => {
timer = setTimeout(function () {
NProgress.start();
}, delay);
};
const stop = () => {
clearTimeout(timer);
NProgress.done();
};
Router.events.on("routeChangeStart", () => load());
Router.events.on("routeChangeComplete", () => stop());
Router.events.on("routeChangeError", () => stop());
}, []);
return <Component {...pageProps} />;
};