Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General approach to showing indicator that page is loading in Next.js?

Sometimes in Next.js when it takes a while to load a page, and there is no indication that the page is changing after you trigger a <Link /> click or router.push change.

For example, say I am on a dictionary site on a word definition. Then I click find all words starting with "a", and it loads a page with a 1000 words starting with "a". It might take 2 or 3 seconds to load and render that page, but during that time there is no indication that the page is "transitioning".

How should you wire in an indicator of some sort in this sort of scenario? What is the recommended approach?

like image 831
Lance Avatar asked Oct 12 '25 10:10

Lance


1 Answers

Not sure about the recommended approach but one way to add a loading indicator during page load is by using the Next.js built-in Router.

You can listen to its routeChangeStart and routeChangeComplete events to show and hide the loading indicator. I implemented it like this:

import { useState, useEffect } from "react";
import Router from "next/router";

const LoadingWidget = () => {
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const handleRouteChangeStart = () => setLoading(true);
    const handleRouteChangeComplete = () => setLoading(false);

    Router.events.on("routeChangeStart", handleRouteChangeStart);
    Router.events.on("routeChangeComplete", handleRouteChangeComplete);

    return () => {
      Router.events.off("routeChangeStart", handleRouteChangeStart);
      Router.events.off("routeChangeComplete", handleRouteChangeComplete);
    };
  }, []);

  return loading ? <div>Loading...</div> : null;
};

export default LoadingWidget;

Then, you can import and render this the LoadingWidget component in your _app.js file or any other component that wraps your entire application.

import LoadingWidget from "../components/LoadingWidget";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <LoadingWidget />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;
like image 137
Zaheer Abbas Avatar answered Oct 16 '25 12:10

Zaheer Abbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!