Renato Pozzi's Blog

Renato Pozzi's Blog

How to Add a Youtube Like Progress Bar in Next.js Application

How to Add a Youtube Like Progress Bar in Next.js Application

Subscribe to my newsletter and never miss my upcoming articles

So, you wanna add to your Next.js app some loading fancy style.

You can do it using nprogress an open-source package, used to add a Youtube Like progress bar to our applications!

So, how do I implement it?

First in first, install it:

npm install --save nprogress

Once the install has been finished, we will create a new ProgressBar component, in order to decouple the logic into a reusable component.

The component code will be:

import React from "react";
import Router from "next/router";
import NProgress from "nprogress";
import { debounce } from "lodash";

import "nprogress/nprogress.css";

export const ProgressBar = React.memo(() => {
  const start = debounce(NProgress.start, 150);

  React.useEffect(() => {"routeChangeStart", () => {
    });"routeChangeComplete", () => {
    });"routeChangeError", () => {
  }, []);

  return <></>;

As you can see, we will use the Next.js router events to manage the progress bar rendering.

When the route starts to change, the start method will be called after 150 milliseconds.

debouncing is good to avoid the progress bar flickering on fast routing change.

Once the route change is complete or goes in error, the start method is canceled and the done method is called, expanding the bar to 100% width.

How do I use it in my app?

You made the component, to use it you can do something like that:

import { ProgressBar } from "./ProgressBar";
import { BaseLayout } from "./BaseLayout";

export const AppWrapper = ({ children, isHome }) => {
  return (
      <ProgressBar />
      <BaseLayout isHome={isHome}>{children}</BaseLayout>

In this case, the AppWrapper is my main component, so at the top, I've inserted the just created ProgressBar.

If you want to see an example, in one of my open-source projects I used this progress bar. You can also check the source code here

So, for today is all. Seyaaa in the next article!

Let's Connect!: Twitter | Linkedin

Share this