
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.
<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.
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
Feature | Normal Routing | Shallow Routing |
---|---|---|
Page re-renders? | β Yes | β No |
Triggers getServerSideProps ? | β Yes | β No |
Good for UI updates? | β No | β Yes |