0
0
NextJSframework~8 mins

Active link detection in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Active link detection
MEDIUM IMPACT
This affects interaction responsiveness and rendering speed when highlighting navigation links based on the current page.
Highlight the active navigation link based on the current URL
NextJS
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;
}
Using CSS classes instead of inline styles reduces style recalculations. Using usePathname hook avoids unnecessary router object overhead. Adding aria-current improves accessibility.
📈 Performance Gainreduces style recalculations and re-renders, improving INP and user experience
Highlight the active navigation link based on the current URL
NextJS
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>
  );
}
Using inline styles and comparing router.pathname on every render causes React to re-render all links and triggers style recalculations frequently.
📉 Performance Costtriggers multiple style recalculations and re-renders on navigation, increasing INP
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Inline style comparison on every renderMultiple style attribute updatesMultiple reflows on navigationHigh paint cost due to style recalculation[X] Bad
CSS class toggling with usePathname hookMinimal DOM updates, class attribute onlySingle reflow per navigationLow paint cost, efficient style recalculation[OK] Good
Rendering Pipeline
Active link detection updates the DOM to reflect the current page state, affecting style calculation and layout if styles change. Efficient detection minimizes reflows and repaints.
Style Calculation
Layout
Paint
⚠️ BottleneckStyle Calculation due to frequent inline style changes or class toggling
Core Web Vital Affected
INP
This affects interaction responsiveness and rendering speed when highlighting navigation links based on the current page.
Optimization Tips
1Use CSS classes instead of inline styles for active link highlighting.
2Use lightweight hooks like usePathname to detect the current route.
3Avoid frequent state updates that cause re-renders on navigation.
Performance Quiz - 3 Questions
Test your performance knowledge
Which approach reduces style recalculations when highlighting an active link in Next.js?
AApplying inline styles directly in the render method
BUsing a global variable to track active link
CUsing CSS classes toggled by a pathname hook
DReloading the page on every link click
DevTools: Performance
How to check: Record a session while navigating links and watch for style recalculation and layout thrashing in the summary. Check the 'Interactions' and 'Rendering' sections.
What to look for: Look for excessive style recalculations or layout shifts when clicking links indicating inefficient active link detection.