Detect when the page/route is loading with custom hook - NextJS

Within NextJS's router there are events that can be captured using Router from next/router.

Below is a simple custom hook that gives you a loading state boolean that you can use anywhere within your NextJS project.

TypeScript

import { Router } from 'next/router';
import { useState } from 'react';

const useLoading = (): boolean => {
    const [loading, setLoading] = useState<boolean>(false);

    Router.events.on('routeChangeStart', () => {
        setLoading(true);
    });

    Router.events.on('routeChangeComplete', () => {
        setLoading(false);
    });

    Router.events.on('routeChangeError', () => {
        setLoading(false);
    });

    return loading;
};

export default useLoading;

JavaScript

import { Router } from 'next/router';
import { useState } from 'react';

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

    Router.events.on('routeChangeStart', () => {
        setLoading(true);
    });

    Router.events.on('routeChangeComplete', () => {
        setLoading(false);
    });

    Router.events.on('routeChangeError', () => {
        setLoading(false);
    });

    return loading;
};

export default useLoading;

Dafydd Thomas

Dafydd Thomas

Wales