ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Shallow Routing in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1746' AND `tutorial_status`=1 LIMIT 1

Shallow Routing in NextJS

πŸš€ Shallow Routing in Next.js

Shallow Routing in Next.js allows updating the URL without re-running data fetching methods like getServerSideProps or getStaticProps. This is useful for UI updates without triggering a full page refresh.


πŸ“Œ 1. Why Use Shallow Routing?

βœ”οΈ Prevents unnecessary re-fetching of data
βœ”οΈ Improves performance by avoiding full re-renders
βœ”οΈ Ideal for filtering, pagination, and UI state updates


πŸ“Œ 2. How Shallow Routing Works

In Next.js, you can use router.push() or router.replace() with the shallow: true option.

javascript

<div> <h1>Dashboard</h1> {/* Navigation Tabs */} <nav> <button onClick={() => router.push("?tab=home", undefined, { shallow: true })}>Home</button> <button onClick={() => router.push("?tab=profile", undefined, { shallow: true })}>Profile</button> </nav> {/* Tab Content */} {tab === "home" && <p>Welcome to the Home tab!</p>} {tab === "profile" && <p>Viewing Profile section.</p>} </div> );}

βœ… Switching tabs updates the URL (?tab=profile) without fetching new data


πŸ“Œ 4. Shallow Routing with replace()

Use replace() instead of push() if you don’t want the update to be stored in browser history.

javascript

router.replace("?tab=profile", undefined, { shallow: true });

βœ… This updates the URL but doesn’t add a new entry in the history stack


πŸ“Œ 5. When to Use Shallow Routing?

βœ… For UI state updates (e.g., switching tabs, filters)
βœ… For search or filter parameters in the URL
βœ… For updating query strings without a full re-fetch

❌ Avoid shallow routing if you need to trigger getServerSideProps() or getStaticProps()


πŸ“Œ 6. Shallow Routing vs. Normal Routing

FeatureNormal RoutingShallow Routing
Page re-renders?βœ… Yes❌ No
Triggers getServerSideProps?βœ… Yes❌ No
Good for UI updates?❌ Noβœ… Yes

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql