Bird
Raised Fist0
NextJSframework~10 mins

Active link detection in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Active link detection
User clicks a link
↓
Next.js Router updates URL
↓
Component checks current URL
↓
Compare link href with current URL
↓
Add active style
↓
Render updated link style
When a user clicks a link, Next.js updates the URL. The component compares the link's href with the current URL. If they match, it adds an active style to highlight the link.
Execution Sample
NextJS
import Link from 'next/link';
import { usePathname } from 'next/navigation';

export default function NavLink({ href, children }) {
  const pathname = usePathname();
  const isActive = pathname === href;
  return <Link href={href} className={isActive ? 'active' : ''}>{children}</Link>;
}
This code defines a NavLink component that highlights itself when its href matches the current URL path.
Execution Table
StepActionCurrent URL (pathname)Link hrefIs Active?Class Applied
1Initial render/home/hometrue'active'
2User clicks link to /about/about/homefalse'' (no class)
3Render NavLink with href='/about'/about/abouttrue'active'
4User clicks link to /contact/contact/aboutfalse'' (no class)
5Render NavLink with href='/contact'/contact/contacttrue'active'
6User clicks link to /home/home/contactfalse'' (no class)
7Render NavLink with href='/home'/home/hometrue'active'
8ExitUser stops clicking, no URL change---
💡 Execution stops when user stops clicking links and URL remains stable.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5After Step 7Final
pathname/home/home/about/contact/home/home
href/home/home/about/contact/home/home
isActivetruefalsetruetruetruetrue
className'active''''active''active''active''active'
Key Moments - 2 Insights
Why does the link get the 'active' class only when pathname equals href?
Because the code compares pathname and href exactly (see execution_table steps 1, 3, 5, 7). Only when they match does isActive become true, adding the 'active' class.
What happens if the pathname is '/about/team' but href is '/about'?
The strict equality check fails, so isActive is false and no 'active' class is added. To handle subpaths, code must check if pathname starts with href.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 3. What is the value of isActive?
Afalse
Btrue
Cundefined
Dnull
💡 Hint
Check the 'Is Active?' column at Step 3 in the execution_table.
At which step does the link with href='/contact' get the 'active' class?
AStep 4
BStep 6
CStep 5
DStep 7
💡 Hint
Look for when pathname and href both equal '/contact' in the execution_table.
If pathname was '/about/team' and href was '/about', what would isActive be with the current code?
Afalse
Bnull
Ctrue
Dthrows error
💡 Hint
The code uses strict equality (pathname === href), so different strings mean false.
Concept Snapshot
Active link detection in Next.js:
- Use usePathname() to get current URL path.
- Compare pathname with link href.
- If equal, add 'active' class to highlight link.
- Helps users see which page they are on.
- For subpaths, use startsWith instead of strict equality.
Full Transcript
Active link detection in Next.js works by checking the current URL path against each link's href. When a user clicks a link, Next.js updates the URL. The NavLink component uses the usePathname hook to get the current path. It compares this path with the link's href. If they match exactly, the component adds an 'active' CSS class to highlight the link. This helps users know which page they are on. The execution table shows how the pathname and href change as the user clicks different links, and when the 'active' class is applied. Beginners often wonder why the active class only appears on exact matches and what happens with subpaths. The code uses strict equality, so only exact matches get the active style. To handle subpaths, the code would need to check if the pathname starts with the href. This visual trace helps learners see how state changes and rendering happen step-by-step in active link detection.

Practice

(1/5)
1. What is the main purpose of active link detection in a Next.js navigation menu?
easy
A. To highlight the link of the current page the user is on
B. To preload all pages linked in the menu
C. To disable links that are not active
D. To change the URL path automatically

Solution

  1. Step 1: Understand active link detection

    Active link detection is used to show which page is currently open by highlighting its link in the navigation.
  2. Step 2: Identify the purpose in Next.js navigation

    Highlighting the current page link helps users know where they are in the site.
  3. Final Answer:

    To highlight the link of the current page the user is on -> Option A
  4. Quick Check:

    Active link detection = Highlight current page link [OK]
Hint: Active link detection means showing current page link highlighted [OK]
Common Mistakes:
  • Thinking it disables other links
  • Confusing with preloading pages
  • Assuming it changes the URL automatically
2. Which Next.js hook is used to get the current URL path for active link detection?
easy
A. useRouter()
B. useHref()
C. usePathname()
D. useLocation()

Solution

  1. Step 1: Recall Next.js hooks for routing

    Next.js provides usePathname() to get the current URL path in the app router.
  2. Step 2: Differentiate from other hooks

    useRouter() is more general, but usePathname() specifically returns the current path string.
  3. Final Answer:

    usePathname() -> Option C
  4. Quick Check:

    Current path hook = usePathname() [OK]
Hint: Use usePathname() to get current URL path in Next.js [OK]
Common Mistakes:
  • Using useRouter() instead of usePathname()
  • Confusing with React Router hooks
  • Using non-existent hooks like useHref()
3. Given this Next.js component snippet, what will be the value of isActive if the current path is /about?
const pathname = usePathname();
const isActive = pathname === '/about';
medium
A. false
B. null
C. undefined
D. true

Solution

  1. Step 1: Understand the usePathname() output

    usePathname() returns the current URL path as a string, here '/about'.
  2. Step 2: Evaluate the comparison

    Comparing pathname === '/about' when pathname is '/about' results in true.
  3. Final Answer:

    true -> Option D
  4. Quick Check:

    Pathname '/about' === '/about' is true [OK]
Hint: Compare pathname string directly to link href for active check [OK]
Common Mistakes:
  • Assuming usePathname() returns an object
  • Using == instead of === causing confusion
  • Expecting false when paths match exactly
4. Identify the error in this Next.js active link detection code:
const pathname = usePathname;
const isActive = pathname === '/home';
medium
A. pathname should be imported from 'next/link'
B. usePathname is not called as a function
C. Comparison operator should be != instead of ===
D. isActive should be a state variable

Solution

  1. Step 1: Check usePathname usage

    usePathname is a hook and must be called as a function: usePathname()
  2. Step 2: Identify the error in assignment

    Assigning usePathname without parentheses assigns the function itself, not the path string.
  3. Final Answer:

    usePathname is not called as a function -> Option B
  4. Quick Check:

    Hooks must be called: usePathname() [OK]
Hint: Always call hooks with () to get their value [OK]
Common Mistakes:
  • Forgetting parentheses on hooks
  • Using wrong comparison operators
  • Importing pathname from wrong module
5. How would you correctly add an aria-current attribute to a Next.js navigation link when it is active using usePathname()? Choose the best code snippet.
hard
A.
const pathname = usePathname();
return <a href='/about' aria-current={pathname === '/about' ? 'page' : undefined}>About</a>;
B.
const pathname = usePathname();
return <a href='/about' aria-current={pathname === '/about' ? true : false}>About</a>;
C.
const pathname = usePathname();
return <a href='/about' aria-current={pathname === '/about' ? 'true' : 'false'}>About</a>;
D.
const pathname = usePathname();
return <a href='/about' aria-current={pathname === '/about' ? 'current' : ''}>About</a>;

Solution

  1. Step 1: Understand aria-current usage

    aria-current should be set to 'page' when the link is active, otherwise omitted or undefined.
  2. Step 2: Check each option's attribute value

    const pathname = usePathname();
    return <a href='/about' aria-current={pathname === '/about' ? 'page' : undefined}>About</a>;
    correctly uses 'page' for active and undefined for inactive, which is the recommended pattern.
  3. Final Answer:

    Option A code snippet -> Option A
  4. Quick Check:

    aria-current='page' when active, undefined otherwise [OK]
Hint: Use aria-current='page' only when link matches current path [OK]
Common Mistakes:
  • Using boolean true/false instead of 'page'
  • Using string 'true' or 'false' incorrectly
  • Setting aria-current to wrong string values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard