Active Links (usePathname)

Reading the current URL path to style navigation.

Next.js3 min readConcept 39 of 65

Reading the Path

usePathname is a Client Component hook that lets you read the current URL's pathname.

For example, if the user is at https://example.com/dashboard/settings, the hook returns the string '/dashboard/settings'.

The Active State

The most common use case in Next.js for usePathname is styling active navigation links.

By comparing the hook's output to a link's href attribute, you can easily apply a different CSS class (like a glowing underline or bold text) to highlight the page the user is currently viewing.

Exact Matching

You import it from next/navigation.

Then, inside your <NavLink> component, you write: const isActive = pathname === href;.

The Active Link

Click the links in the mock navigation bar below. Watch how the usePathname hook dynamically updates, and how that string is compared against each link's href to determine the active glow state.

https://acme.com/dashboard
Navbar.tsx
const pathname = usePathname();
// Returns: "/dashboard"
Boolean Comparisons
const isActive = pathname === "/";
//false
const isActive = pathname === "/dashboard";
//true
const isActive = pathname === "/shop";
//false
const isActive = pathname === "/blog";
//false

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If a user visits `https://acme.com/store/shoes?size=10`, what will `usePathname()` return?

Remember this

  • usePathname is a Client Component hook.
  • It is primarily used for styling 'active' states on navigation bars.
  • It strips out the domain name.
  • It completely ignores query parameters (?key=value).

Done with this concept?

Mark it complete to track your progress. No login needed.