Linking & Navigating

In a traditional HTML website, moving between pages is done using the standard <a href="..."> element. However, this causes a full browser page refresh. In Next.js, as a Single Page Application (SPA), we want to performclient-side navigation where the page transitions instantaneously without reloading the browser instance.

The `next/link` Component

Next.js provides a built-in React component called Link to handle fast, client-side routing between pages.

import Link from 'next/link';

export default function NavigationBar() {
  return (
    <nav>
      {/* Standard Link */}
      <Link href="/about">About Us</Link>
      
      {/* Dynamic Link */}
      <Link href="/blog/my-first-post">Read Post</Link>
    </nav>
  );
}

Why use `next/link`?

  • Pre-fetching: In the background, Next.js automatically pre-fetches the code for the linked page whenever the Link becomes visible in the user's viewport. Thus, clicking it results in near-instant transitions.
  • Client-side state preservation: Unlike a full refresh, React state or contexts persist during navigation.
  • Accessibility: It still returns a native <a> tag to the DOM, preserving SEO and screen reader capability.

Navigating Programmatically using `useRouter`

Sometimes you cannot use a `Link` component—for example, if a user submits a login form, and you want to redirect them to a dashboard programmatically after the fetch request resolves.

In the Pages Router, you import useRouter from next/router. In the App Router, you must import it from next/navigation.

'use client'; // Required in App router when using React Hooks!
import { useRouter } from 'next/navigation';

export default function LoginForm() {
  const router = useRouter();

  const handleLogin = async (e) => {
    e.preventDefault();
    const success = await loginUser(); // Mock function

    if (success) {
      // Programmatic Redirect
      router.push('/dashboard');
    }
  };

  return (
    <form onSubmit={handleLogin}>
      <button type="submit">Login</button>
    </form>
  );
}

Other Router Methods

The router object provides various other methods for managing navigation:

  • router.replace('/url'): Replaces the current history state. Useful for login redirections so the user cannot press their browser 'Back' button to return to the login form.
  • router.back(): Navigates back one step in the browser's history queue.
  • router.refresh(): (App Router Only) Refresches the current route and refetches data on the server without losing client-side React state.

Conclusion

By correctly using next/link, your application achieves instantaneous loading times through intelligent prefetching. Next, we'll discover how we can pre-render data on the server using Next.js Server-Side Rendering (SSR).