Next.js Navigation & Link
The Next.js Link component is the primary way to move between pages without a full browser reload. It wraps a normal anchor tag and adds client-side navigation, prefetching, and automatic scroll handling. Using it correctly makes your app feel fast and responsive.
This tutorial covers the Link component, its props, and the hooks that handle programmatic navigation and active link styling. You will build a navigation bar that highlights the current page and a button that redirects after a click. If you are new to routing, start with Next.js Pages & Layouts first.
What Is the Next.js Link Component and Why Use It?
The Next.js Link component is a built-in wrapper around the HTML anchor tag. It enables client-side navigation, meaning the browser does not request a new HTML page from the server. Instead, Next.js fetches the new route's data and swaps the content in place. Link also prefetches routes automatically when they enter the viewport .
A plain <a> tag triggers a full page reload. The browser discards all JavaScript state and starts over. Link avoids this by using the App Router's client-side navigation system. The result is faster transitions and preserved layout state.
// app/page.tsx
import Link from "next/link";
export default function HomePage() {
return (
<main>
<h1>Home</h1>
<Link href="/about">Go to About</Link>
</main>
);
}
Browser shows:
Home
Go to About ← clicking this changes the URL to /about without a full reload
How it works: Link renders an anchor element in the HTML for accessibility and SEO. When clicked, Next.js intercepts the navigation, fetches the /about route, and updates the page without reloading the browser. The address bar changes, and the back button works normally.
How Does Link Handle Dynamic Segments and Special Props?
Link accepts a string href or a template literal for dynamic routes. It also has two props that control scrolling and history behavior: scroll and replace .
Dynamic Segments with Template Literals
// app/blog/page.tsx
import Link from "next/link";
const posts = [
{ slug: "first-post", title: "First Post" },
{ slug: "second-post", title: "Second Post" },
];
export default function BlogListPage() {
return (
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
);
}
How it works: The template literal builds the URL path from each post's slug. Next.js matches it to the dynamic route file app/blog/[slug]/page.tsx. The Next.js Dynamic Routes tutorial covers the folder convention in detail.
scroll and replace Props
// app/help/page.tsx
import Link from "next/link";
export default function HelpPage() {
return (
<main>
<h1>Help</h1>
<Link href="/faq" scroll={false}>FAQ (keep scroll position)</Link>
<Link href="/login" replace>Login (no history entry)</Link>
</main>
);
}
How it works: By default, navigating to a new page scrolls to the top. scroll={false} keeps the current scroll position. The replace prop replaces the current history entry instead of adding a new one, so the user cannot press Back to return to the previous page. This is useful for login redirects.
How Do You Navigate Programmatically with useRouter?
The useRouter hook from next/navigation lets you change routes from code, such as after a button click or a form submission. It only works inside Client Components, so the file needs "use client" .
// app/components/NavigateButton.tsx
"use client";
import { useRouter } from "next/navigation";
export default function NavigateButton() {
const router = useRouter();
return (
<button onClick={() => router.push("/dashboard")}>
Go to Dashboard
</button>
);
}
Browser shows:
Go to Dashboard ← clicking pushes the /dashboard route into history
How it works: router.push navigates to the new route and adds an entry to the browser history stack. router.replace does the same but replaces the current entry. router.back goes to the previous page. router.refresh re-fetches the current route's data without a full reload . Remember: import useRouter from next/navigation, not next/router. The latter is the legacy Pages Router import.
How Do You Highlight the Active Link with usePathname?
The usePathname hook returns the current URL path as a string. You compare it to each link's href to decide whether the link is active. This replaces the old router.pathname pattern from the Pages Router .
// app/components/NavBar.tsx
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
const links = [
{ href: "/", label: "Home" },
{ href: "/about", label: "About" },
{ href: "/dashboard", label: "Dashboard" },
];
export default function NavBar() {
const pathname = usePathname();
return (
<nav>
{links.map((link) => {
const isActive = pathname === link.href;
return (
<Link
key={link.href}
href={link.href}
style={{ fontWeight: isActive ? "bold" : "normal" }}
>
{link.label}
</Link>
);
})}
</nav>
);
}
Browser shows at /about:
Home About (bold) Dashboard
How it works: usePathname returns the current path, such as /about. The component compares it to each link's href. When they match, isActive is true and the style changes. For routes with sub-paths, you can use pathname.startsWith(link.href) instead of strict equality .
How Does redirect Work in Server Components?
The redirect function from next/navigation sends the user to another URL from a Server Component. It throws a special error that Next.js catches and converts into an HTTP redirect response .
// app/admin/page.tsx
import { redirect } from "next/navigation";
export default async function AdminPage() {
const isLoggedIn = false;
if (!isLoggedIn) {
redirect("/login");
}
return <h1>Admin Panel</h1>;
}
Browser behavior: navigating to /admin while not logged in
redirects to /login automatically.
How it works: When redirect is called, Next.js stops rendering the current route and sends a redirect response to the browser. The function does not return, so you do not need to write return redirect(). In Server Actions and Route Handlers, redirect should be called outside try/catch blocks because it works by throwing an error.
How Does Prefetching Make Navigation Faster?
Link automatically prefetches routes when they become visible in the viewport. Prefetching means Next.js loads the route's code and data in the background before the user clicks. When the click happens, the transition feels instant .
| Route Type | Prefetch Behavior |
|---|---|
| Static routes | The entire route is prefetched and cached by default. |
| Dynamic routes | Only the shared layout up to the first loading.tsx is prefetched and cached for 30 seconds. |
Prefetching runs only in production, not in development mode. You can disable it per link with prefetch={false}, but most of the time the default is fine. The benefit is fewer loading spinners and faster perceived performance.
Common Mistakes and Best Practices
- Importing
useRouterfromnext/router. In the App Router, the correct import isnext/navigation. The old path is for the Pages Router and will not work in theappdirectory. - Using
<a>for internal links. A plain anchor causes a full page reload and loses client state. UseLinkfor every route inside your Next.js app. - Forgetting
"use client"when using hooks.useRouterandusePathnameonly work in Client Components. Without the directive, Next.js throws an error. - Comparing pathnames without handling sub-routes.
pathname === "/blog"will not highlight the Blog link when the user is at/blog/first-post. UsestartsWithfor parent links if you want them active on child pages. - Calling
router.pushwith unsanitized input. Never pass user-controlled strings directly torouter.pushorrouter.replace. Malicious URLs can execute scripts in your page context.
Real-World Example: A Navigation Bar with Active Highlight and a Redirect Button
This example combines a NavBar Client Component that highlights the active link, and a separate button component that navigates programmatically.
app/
layout.tsx
components/
NavBar.tsx
GoToDashboard.tsx
page.tsx
about/
page.tsx
dashboard/
page.tsx
// app/components/NavBar.tsx
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
const links = [
{ href: "/", label: "Home" },
{ href: "/about", label: "About" },
{ href: "/dashboard", label: "Dashboard" },
];
export default function NavBar() {
const pathname = usePathname();
return (
<nav>
{links.map((link) => {
const isActive = pathname === link.href;
return (
<Link
key={link.href}
href={link.href}
style={{ fontWeight: isActive ? "bold" : "normal" }}
>
{link.label}
</Link>
);
})}
</nav>
);
}
// app/components/GoToDashboard.tsx
"use client";
import { useRouter } from "next/navigation";
export default function GoToDashboard() {
const router = useRouter();
return (
<button onClick={() => router.push("/dashboard")}>
Open Dashboard
</button>
);
}
Line-by-line explanation: The NavBar file starts with "use client" because it uses usePathname, a client-side hook. It imports Link from next/link and the hook from next/navigation. The links array holds the route and label for each navigation item. Inside the component, pathname gives the current URL. The map loop builds a Link for each entry. When pathname equals the link's href, the font weight becomes bold. The GoToDashboard component uses useRouter to get the router instance. The button's click handler calls router.push("/dashboard"), which navigates without a full reload. Both components live in app/components/ and can be imported into app/layout.tsx to appear on every page.
Summary
- The Next.js Link component enables client-side navigation and replaces the plain anchor tag for internal routes.
Linkprefetches visible routes automatically, making transitions feel instant in production.- Use
useRouterfromnext/navigationfor programmatic navigation. Import it fromnext/navigation, notnext/router. usePathnamereturns the current path. Compare it to link hrefs to highlight the active link.redirectworks in Server Components and sends an HTTP redirect response.- Common props like
scrollandreplacecontrol scroll behavior and history entries.
Now that you can navigate between static pages, continue to Next.js Dynamic Routes to learn how to build routes that accept parameters in the URL.
Frequently Asked Questions
Can I use a normal anchor tag instead of Link in Next.js?
You can, but it causes a full page reload. The browser discards all JavaScript state, and the layout remounts. Use Link for any route inside your Next.js app. Reserve plain <a> tags for external websites, email links, or downloadable files.
Why is useRouter not working in my component?
useRouter only works in Client Components. Add "use client" at the very top of the file before any imports. Also check that you imported it from next/navigation, not next/router. The Pages Router import does not work in the app directory.
Does Link prefetch every route on the page?
Link prefetches routes when they become visible in the viewport. Links below the fold are prefetched only after the user scrolls them into view. Prefetching also runs only in production mode, not during development. You can disable it per link with prefetch={false}.
How do I make a link active for child routes?
Use pathname.startsWith(link.href) instead of strict equality. For example, "/blog" should be active when the path is "/blog/first-post". Handle the root path "/" separately with strict equality, otherwise every route would highlight the Home link.
What is the difference between router.push and redirect?
router.push is a client-side navigation method from the useRouter hook. It works in event handlers inside Client Components. redirect is a server-side function that throws an error and sends an HTTP redirect response. Use router.push for button clicks and redirect for server-side conditions like authentication checks.
Practice Exercises
Easy: Create a Basic Link
Create a page at app/contact/page.tsx with a heading. On the home page, add a Link that navigates to /contact.
Show solution
// app/page.tsx
import Link from "next/link";
export default function HomePage() {
return (
<main>
<h1>Home</h1>
<Link href="/contact">Contact Us</Link>
</main>
);
}
// app/contact/page.tsx
export default function ContactPage() {
return <h1>Contact</h1>;
}
Link handles the navigation without a full page reload.
Easy: Add a replace Link
Create a link to /login that uses the replace prop. Explain what happens to the browser history.
Show solution
// app/page.tsx
import Link from "next/link";
export default function HomePage() {
return <Link href="/login" replace>Login</Link>;
}
The replace prop replaces the current history entry. The user cannot press Back to return to the previous page.
Medium: Highlight Active Link
Build a two-link navigation component for / and /about. Use usePathname to add bold styling to the active link.
Show solution
// app/components/SimpleNav.tsx
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
export default function SimpleNav() {
const pathname = usePathname();
return (
<nav>
<Link href="/" style={{ fontWeight: pathname === "/" ? "bold" : "normal" }}>
Home
</Link>
<Link
href="/about"
style={{ fontWeight: pathname === "/about" ? "bold" : "normal" }}
>
About
</Link>
</nav>
);
}
usePathname returns the current path, and the style changes based on a strict match.
Challenge: Redirect Button with useRouter
Create a Client Component with a button. When clicked, the button calls router.push to navigate to /dashboard. The button should appear on the home page.
Show solution
// app/components/DashboardButton.tsx
"use client";
import { useRouter } from "next/navigation";
export default function DashboardButton() {
const router = useRouter();
return (
<button onClick={() => router.push("/dashboard")}>
Go to Dashboard
</button>
);
}
// app/page.tsx
import DashboardButton from "./components/DashboardButton";
export default function HomePage() {
return (
<main>
<h1>Home</h1>
<DashboardButton />
</main>
);
}
useRouter from next/navigation provides the push method for programmatic navigation.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
