0
0
NextJSframework~5 mins

Shallow routing concept in NextJS

Choose your learning style9 modes available
Introduction

Shallow routing lets you change the URL without reloading the whole page. This makes your app faster and smoother.

When you want to update the URL query or path but keep the current page state.
When building filters or tabs that change the URL but don't need a full page reload.
When you want to keep user input or scroll position while changing the URL.
When you want to improve user experience by avoiding unnecessary data fetching.
When you want to share a URL that reflects the current view without reloading.
Syntax
NextJS
import { useRouter } from 'next/router';

const router = useRouter();

router.push(url, undefined, { shallow: true });

The shallow: true option tells Next.js to avoid running getServerSideProps or getStaticProps again.

Only the URL changes and the page stays the same component instance.

Examples
Change the URL query to ?tab=1 without reloading the page.
NextJS
router.push('/about?tab=1', undefined, { shallow: true });
Replace the current URL with a new query, keeping the page state intact.
NextJS
router.replace('/profile?section=posts', undefined, { shallow: true });
Sample Program

This component shows three tabs. Clicking a tab changes the URL query ?tab=... using shallow routing. The page does not reload, and the content updates smoothly.

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

export default function ShallowRoutingDemo() {
  const router = useRouter();
  const [tab, setTab] = useState('home');

  useEffect(() => {
    if (router.isReady) {
      setTab(router.query.tab || 'home');
    }
  }, [router.isReady, router.query.tab]);

  function changeTab(newTab) {
    setTab(newTab);
    router.push(`/?tab=${newTab}`, undefined, { shallow: true });
  }

  return (
    <main>
      <h1>Shallow Routing Demo</h1>
      <nav>
        <button onClick={() => changeTab('home')} aria-pressed={tab === 'home'}>Home</button>
        <button onClick={() => changeTab('profile')} aria-pressed={tab === 'profile'}>Profile</button>
        <button onClick={() => changeTab('settings')} aria-pressed={tab === 'settings'}>Settings</button>
      </nav>
      <section aria-live="polite">
        {tab === 'home' && <p>You are on the Home tab.</p>}
        {tab === 'profile' && <p>You are on the Profile tab.</p>}
        {tab === 'settings' && <p>You are on the Settings tab.</p>}
      </section>
    </main>
  );
}
OutputSuccess
Important Notes

Shallow routing only works for the same page. Navigating to a different page reloads normally.

Use shallow routing to keep UI state and avoid slow page reloads.

Summary

Shallow routing changes the URL without full page reload.

It keeps the current page component and state intact.

Useful for tabs, filters, and smooth user experience.