← Back to Blog

Active Nav Tab Not Syncing with URL

By Amin

What Was Happening

The navbar used a local React state (activeTab) to track which tab was "active":

js

const [activeTab, setActiveTab] = useState("Home");

It only updated when the user clicked directly on a nav link:

js

onClick={() => setActiveTab(item.name)}

So if navigation happened from anywhere else — a button, a redirect, a programmatic router.push(), or a back/forward browser action — the URL would change, but activeTab stayed the same. The highlighted tab was out of sync with the actual page.


Root Cause

The active tab was driven by component state, not by the actual URL. These two sources of truth can easily diverge in Next.js apps where navigation can be triggered from many places.


The Fix

Replace the manual state with usePathname() from next/navigation, which always reflects the current URL:

js

const pathname = usePathname();

Then derive isActive directly from it:

js

const isActive = pathname === item.url;

Now there's a single source of truth — the URL itself. No matter how the user navigates (clicking a nav link, pressing a button, using the browser back/forward, or a programmatic redirect), the navbar always reads the current path and highlights the correct tab automatically.


Key Takeaway

Never use local state to track something that is already represented in the URL. In Next.js, usePathname() gives you that value reactively — use it instead of maintaining a parallel state that can go out of sync.