JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
junior
navigation

How do you navigate between pages in Next.js?

nextjs
navigation
link
useRouter
prefetching
routing
Quick Answer

Next.js provides the `Link` component for declarative client-side navigation and the `useRouter` hook for programmatic navigation, both enabling fast page transitions without full page reloads.

Detailed Explanation

Navigation Methods:

  1. <Link> Component (preferred)

    • Client-side navigation between routes
    • Automatic prefetching of linked pages
    • No full page reload
  2. useRouter Hook

    • Programmatic navigation in event handlers
    • Access to route information
    • Methods: push(), replace(), back(), forward()
  3. redirect() Function

    • Server-side redirects in Server Components
    • Use in data fetching or server actions

Prefetching:

  • Links in the viewport are automatically prefetched
  • Disable with prefetch={false}
  • Production only (not in development)

Active Link Styling:

  • Use usePathname() to check current route
  • Apply conditional classes for active state

Code Examples

Link component usage
import Link from 'next/link';

export default function Navigation() {
  return (
    <nav>
      {/* Basic link */}
      <Link href="/">Home</Link>
      
      {/* Link with dynamic route */}
      <Link href="/posts/123">Post 123</Link>
      
      {/* Link with query params */}
      <Link href="/search?q=nextjs">Search</Link>
      
      {/* Link with object href */}
      <Link
        href={{
          pathname: '/posts/[id]',
          query: { id: '456' },
        }}
      >
        Post 456
      </Link>
      
      {/* Disable prefetching */}
      <Link href="/heavy-page" prefetch={false}>
        Heavy Page
      </Link>
      
      {/* Replace history instead of push */}
      <Link href="/login" replace>
        Login
      </Link>
    </nav>
  );
}

Resources

Next.js Link Component

docs

useRouter Hook

docs

Related Questions

How does file-based routing work in Next.js?

junior
routing

What are the key differences between Pages Router and App Router in Next.js?

mid
routing
Previous
How does file-based routing work in Next.js?
Next
What is next/image and why should you use it over the regular img tag?