Next.js - Shallow Routing



In Next.js, shallow routing is a navigation technique that allows you to change the URL of a page, without reloading the page. In this chapter, we will learn what is shallow routing, how to implement it and benefits of using it.

What is Shallow Routing?

Shallow routing is a routing method in Next.js in which the URL update occur without re-rendering or reloading the entire page. This method avoid re-executing of data fetching methods like getServerSideProps, getStaticProps, and getInitialProps. It provides a way to modify the URL and route state without losing the current page's context or performance.

Implementing Shallow Routing

Next.js provides the useRouter hook to implement shallow routing. To enable shallow routing, set the shallow option to true inside object of useRouter. See the example below.

Example

In the following example, we created a button which on clicked counts of steps are increased and it will be updated in URL.

'use client';

import { useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';

export default function ShallowRoutingExample() {
  const router = useRouter();
  const [step, setStep] = useState(1);

  const handleRouteChange = () => {
    const nextStep = step + 1;
    setStep(nextStep); // Update local state
    // Update the URL without reloading the page
    router.push(`/shallow-routing?step=${nextStep}`,{ shallow: true });
  };

  return (
    <div>
        <h1>Shallow Routing Example</h1>
        <p>
            Current step: <strong>{step}</strong>
        </p>
        <button
            onClick={handleRouteChange}
        >
            Next Step
        </button>
    </div>
  );
}

Output

In the output, the count of steps is changing on URL.

next.js-shallow-routing

Benefits of Shallow Routing

Shallow routing offers several advantages:

  • Maintains current page state during URL updates
  • Prevents unnecessary data refetching
  • Improves performance by avoiding full page reloads
  • Enables dynamic URL modifications without disrupting user experience
Advertisements