Performance: Active link detection
This affects interaction responsiveness and rendering speed when highlighting navigation links based on the current page.
import Link from 'next/link'; import { usePathname } from 'next/navigation'; export default function Nav() { const pathname = usePathname(); return ( <nav> {['/', '/about', '/contact'].map((path) => { const isActive = pathname === path; return ( <Link key={path} href={path} className={isActive ? 'active-link' : ''} aria-current={isActive ? 'page' : undefined} > {path === '/' ? 'Home' : path.slice(1)} </Link> ); })} </nav> ); } /* CSS */ .active-link { color: red; }
import { useRouter } from 'next/router'; export default function Nav() { const router = useRouter(); return ( <nav> {['/', '/about', '/contact'].map((path) => ( <a key={path} href={path} style={{ color: router.pathname === path ? 'red' : 'black' }} > {path === '/' ? 'Home' : path.slice(1)} </a> ))} </nav> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline style comparison on every render | Multiple style attribute updates | Multiple reflows on navigation | High paint cost due to style recalculation | [X] Bad |
| CSS class toggling with usePathname hook | Minimal DOM updates, class attribute only | Single reflow per navigation | Low paint cost, efficient style recalculation | [OK] Good |
isActive if the current path is /about?
const pathname = usePathname(); const isActive = pathname === '/about';
const pathname = usePathname; const isActive = pathname === '/home';
aria-current attribute to a Next.js navigation link when it is active using usePathname()? Choose the best code snippet.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.Pass the test and this pattern moves unknown