Loading Screen on Next.js page transition

Using the new hook api,
this is how I would do it..

function Loading() {
    const router = useRouter();

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

    useEffect(() => {
        const handleStart = (url) => (url !== router.asPath) && setLoading(true);
        const handleComplete = (url) => (url === router.asPath) && setLoading(false);

        router.events.on('routeChangeStart', handleStart)
        router.events.on('routeChangeComplete', handleComplete)
        router.events.on('routeChangeError', handleComplete)

        return () => {
            router.events.off('routeChangeStart', handleStart)
            router.events.off('routeChangeComplete', handleComplete)
            router.events.off('routeChangeError', handleComplete)
    return loading && (<div>Loading....{/*I have an animation here*/}</div>);

Now <Loading/> is going to show up whenever the route will change…
I animate this using react-spring, but you can use any library you prefer to do this.

You can even take a step further and modify when the component shows up by modifying the handleStart and handleComplete methods that gets a url.

Leave a Comment