Skip to content

Chapter 7 of 8

Navigation Hooks and Components

Navigation is a first-class concern in Next.js, and the framework provides both declarative and programmatic ways to move between routes. The <Link> component from next/link is the preferred way to navigate. It performs client-side transitions without a full page reload and, by default, prefetches the destination when the link enters the viewport, so the next page is essentially instant.

Static routes are fully prefetched, while dynamic routes are prefetched only up to the nearest loading.tsx boundary, which keeps prefetching costs bounded. You can opt out of prefetching on a per-link basis with prefetch={false} when the destination is unlikely to be visited or is expensive to load.

For programmatic navigation in Client Components, the useRouter hook from next/navigation exposes methods like router.push('/path') to navigate, router.replace('/path') to swap the current history entry, router.refresh() to re-fetch the current route's Server Components, and router.back() to move to the previous page. Two companion hooks are also worth knowing. The usePathname hook returns the current URL pathname as a string, which is handy for highlighting the active link in a navigation menu. The useSearchParams hook returns a read-only URLSearchParams object representing the query string, allowing you to read parameters like ?q=hello through searchParams.get('q'). Together with <Link>, they cover virtually every navigation pattern a typical application requires.

All chapters
  1. 1Foundations of Next.js and the App Router
  2. 2Server and Client Components
  3. 3Rendering Strategies
  4. 4Advanced Routing Patterns
  5. 5Layouts, Templates, and Special Files
  6. 6Data Fetching, Mutations, and Middleware
  7. 7Navigation Hooks and Components
  8. 8Configuration, Metadata, and Optimization

Drill it

Reading is not remembering. These come from the Nextjs Framework deck:

Q

What is Next.js?

Next.js is a React framework created by Vercel that provides features like server-side rendering, static site generation, file-based routing, and API routes out...

Q

What is the App Router in Next.js?

The App Router (introduced in Next.js 13) uses the app/ directory and supports React Server Components, nested layouts, streaming, and colocation of files. It r...

Q

How does file-based routing work in the App Router?

Routes are defined by the folder structure inside app/. A route is created by adding a page.tsx file inside a folder. For example, app/about/page.tsx maps to th...

Q

What is a Server Component in Next.js?

A Server Component renders on the server and sends HTML to the client. It is the default in the App Router. Server Components can directly access databases, rea...