Skip to content

Instantly share code, notes, and snippets.

@adamduncan
Created January 16, 2021 18:58
Show Gist options
  • Save adamduncan/2e5b9c2eafe74fd9fda902a6ea213ba3 to your computer and use it in GitHub Desktop.
Save adamduncan/2e5b9c2eafe74fd9fda902a6ea213ba3 to your computer and use it in GitHub Desktop.
Next.js Router status hook
import { useState, useEffect } from 'react';
import Router from 'next/router';
export default function useRouterStatus() {
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [error, setError] = useState();
useEffect(() => {
const start = () => {
setIsLoading(true);
};
const complete = () => {
setIsLoading(false);
setIsError(false);
setError();
};
const error = error => {
setIsLoading(false);
setIsError(true);
setError(error);
};
Router.events.on('routeChangeStart', start);
Router.events.on('routeChangeComplete', complete);
Router.events.on('routeChangeError', error);
return () => {
Router.events.off('routeChangeStart', start);
Router.events.off('routeChangeComplete', complete);
Router.events.off('routeChangeError', error);
};
}, []);
return { isLoading, isError, error };
}
@husleuujii
Copy link

how to use this hook?

@adamduncan
Copy link
Author

Can be used at the page or component level, to access status of Next's router. For example:

function SomePage() {
  const { isLoading, isError, error } = useRouterStatus();

  if (isError) {
    return <p>{error}</p>;
  }

  if (isLoading) {
    return <p>Loading...</p>;
  }

  return (
    <>
      <h1>Page content</h1>
      <p>All good</p>
    </>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment