Labs ICT
โญ Pro Login

Link Component

Link Component

The Next.js Link component is a wrapper around HTML anchor tags that provides client-side navigation. It's one of the most important components you'll use in your applications.

When you use regular anchor tags, clicking a link causes a full page reload. The Link component prevents this by intercepting clicks and performing client-side navigation instead.

Basic Usage

Using the Link component is straightforward. Import it from next/link and use it just like an anchor tag:

import Link from 'next/link';

export default function Navigation() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/contact">Contact</Link>
    </nav>
  );
}

The href prop specifies the destination URL. The component renders as an anchor tag but provides much better performance.

Preloading

One of Link's best features is automatic preloading. When a Link component enters the viewport, Next.js automatically prefetches the linked page. This makes navigation feel instant.

You can control this behavior with the prefetch prop:

// Disable prefetching for less important links
<Link href="/terms" prefetch={false}>
  Terms of Service
</Link>

By default, prefetching is enabled for visible links. For most applications, the default behavior works perfectly.

Styling the Link Component

The Link component doesn't add any default styles. You can style it just like any other element using CSS classes or styled-components:

import Link from 'next/link';

export default function NavLink({ href, children }) {
  return (
    <Link 
      href={href}
      className="nav-link"
    >
      {children}
    </Link>
  );
}

You can also use the legacyBehavior prop if you need to wrap the Link with an anchor tag for styling purposes. This is useful when migrating from older Next.js versions.

Active Links

Creating active links that highlight the current page is a common requirement. You can achieve this using the usePathname hook:

'use client';
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 pattern creates a reusable NavLink component that automatically highlights when its route is active.

๐Ÿงช Quick Quiz

What is the Link component used for in Next.js?