🐶
Next.js

Next.js Routing: Link vs. push() vs. a Tag

By Filip on 10/05/2024

Explore the distinctions between Next.js Link, router.push, and the a tag for efficient and SEO-friendly navigation in your Next.js applications.

Next.js Routing: Link vs. push() vs. a Tag

Table of Contents

Introduction

Next.js provides several ways to navigate within your application. This article will explore three common methods: the <Link> component, router.push, and the traditional <a> tag, highlighting their differences and use cases.

Step-by-Step Guide

Next.js offers various ways to handle navigation within your application. Let's explore three common methods: the <Link> component, router.push, and the traditional <a> tag, understanding their differences and use cases.

1. The <Link> Component

  • Purpose: Designed for internal navigation between pages within your Next.js app.
  • Benefits:
    • Prefetching: Automatically prefetches pages in the background, leading to faster loading times when users click the link.
    • Client-side transitions: Enables smooth transitions between pages without full page reloads, enhancing user experience.
    • Active link styling: Easily style active links to provide visual feedback to users.

Example:

import Link from 'next/link';

function Nav() {
  return (
    <nav>
      <Link href="/">
        <a>Home</a>
      </Link>
      <Link href="/about">
        <a>About</a>
      </Link>
    </nav>
  );
}

2. router.push

  • Purpose: Programmatic navigation, allowing you to change the route based on user interactions or other logic within your components.
  • Benefits:
    • Dynamic routing: Construct URLs dynamically based on data or user input.
    • Conditional navigation: Navigate based on specific conditions or events.

Example:

import { useRouter } from 'next/router';

function Button() {
  const router = useRouter();

  const handleClick = () => {
    router.push('/contact');
  };

  return (
    <button onClick={handleClick}>Contact Us</button>
  );
}

3. The <a> Tag

  • Purpose: Traditional HTML anchor tag for linking to external websites or resources outside your Next.js app.
  • Considerations:
    • Full page reloads: Clicking an <a> tag triggers a full page reload, which can be slower than client-side transitions.
    • SEO implications: Search engines may treat internal links differently than external links.

Example:

function ExternalLink() {
  return (
    <a href="https://www.example.com">Visit Example.com</a>
  );
}

Choosing the Right Method

  • Internal navigation with prefetching and smooth transitions: Use <Link>.
  • Dynamic or conditional navigation based on logic: Use router.push.
  • Linking to external websites or resources: Use <a> tag.

Additional Tips

  • Explore the as prop in <Link> to customize the URL displayed in the browser while maintaining the correct internal routing.
  • Utilize the shallow prop in router.push to update the URL without causing a full page reload.
  • Consider using Next.js router events like routeChangeStart to implement custom logic during navigation transitions.

By understanding these navigation methods, you can build a Next.js application with efficient and user-friendly routing.

Code Example

This code demonstrates three ways to handle navigation in a Next.js application. The first example uses the Link component from next/link to create internal links within the application. The second example uses the useRouter hook and router.push to programmatically navigate to a search results page based on user input. The third example uses the traditional <a> tag for linking to external websites, ensuring that the links open in a new tab with appropriate security measures.

Here's a breakdown of the JavaScript code for each navigation method mentioned in the article:

1. <Link> Component Example:

import Link from 'next/link';

function Navigation() {
  return (
    <nav>
      <Link href="/">
        <a>Home</a>
      </Link>
      <Link href="/about">
        <a>About</a>
      </Link>
      <Link href="/blog/post-1">
        <a>Blog Post 1</a>
      </Link>
    </nav>
  );
}

Explanation:

  • We import the Link component from next/link.
  • Inside the Navigation component, we use Link for each navigation item.
  • The href prop specifies the path or URL to navigate to.
  • The content within the Link (in this case, <a>) is rendered as a clickable link.

2. router.push Example:

import { useRouter } from 'next/router';

function SearchBox() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    router.push(`/search?q=${searchTerm}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)} 
      />
      <button type="submit">Search</button>
    </form>
  );
}

Explanation:

  • We import useRouter from next/router to access the routing functionalities.
  • We use useState to manage the search term entered by the user.
  • On form submission, we prevent default behavior and use router.push to navigate to the search results page, dynamically constructing the URL with the search term.

3. <a> Tag Example:

function Footer() {
  return (
    <footer>
      <p>External Links:</p>
      <a href="https://www.example.com" target="_blank" rel="noopener noreferrer">
        Example Website
      </a>
      <a href="https://www.github.com" target="_blank" rel="noopener noreferrer">
        GitHub
      </a>
    </footer>
  );
}

Explanation:

  • We use the traditional <a> tag for external links.
  • The href attribute specifies the external URL.
  • We add target="_blank" to open the link in a new tab and rel="noopener noreferrer" for security reasons.

Additional Notes

While the article provides a solid foundation, let's explore some additional nuances and advanced techniques for navigation in Next.js:

Dynamic Route Parameters:

  • Next.js allows you to create dynamic routes using brackets [] in file names (e.g., [id].js). This enables you to capture dynamic segments in the URL and access them within your page component using useRouter.

Nested Routes:

  • Organize your application with nested routes by creating folders within the pages directory. This helps maintain a clean structure and reflects the hierarchy of your content.

Customizing <Link> Behavior:

  • The <Link> component offers various props for fine-tuning its behavior:
    • passHref: Forwards the href prop to the underlying <a> tag, useful for SEO and accessibility.
    • replace: Replaces the current history entry instead of pushing a new one, preventing users from going back to the previous page.
    • scroll: Controls whether the browser should scroll to the top of the page after navigation.

Imperative Navigation with router.replace:

  • Similar to router.push, router.replace allows programmatic navigation but replaces the current history entry instead of creating a new one.

Data Fetching and Navigation:

  • Next.js offers various data fetching methods like getStaticProps and getServerSideProps. These methods can be used to fetch data before rendering a page, ensuring a smooth user experience during navigation.

404 Pages and Error Handling:

  • Create a custom 404 page by adding a 404.js file to your pages directory. This page will be displayed when a user tries to access a non-existent route.

Client-side Data Fetching:

  • For data that needs to be fetched on the client-side after navigation, consider using the useEffect hook or libraries like SWR or React Query.

Lazy Loading and Code Splitting:

  • Next.js automatically code splits your application, but you can further optimize by using dynamic imports to lazy load components only when needed.

Navigation and SEO:

  • Pay attention to SEO best practices when using client-side routing. Ensure that your pages have appropriate titles, meta descriptions, and structured data. Consider server-side rendering for pages that are critical for SEO.

Accessibility Considerations:

  • Make sure your navigation is accessible to users with disabilities. Use semantic HTML elements, provide clear focus management, and ensure keyboard navigation works as expected.

By mastering these advanced techniques, you can build sophisticated and performant Next.js applications with seamless navigation experiences.

Summary

Method Purpose Benefits Considerations
<Link> Internal navigation between pages within your Next.js app. Prefetching, client-side transitions, active link styling. N/A
router.push Programmatic navigation based on user interactions or logic. Dynamic routing, conditional navigation. N/A
<a> tag Linking to external websites or resources outside your app. Traditional HTML anchor tag functionality. Full page reloads, SEO implications for internal links.

Choosing the Right Method:

  • Internal navigation with smooth transitions: <Link>
  • Dynamic/conditional navigation: router.push
  • External links: <a> tag

Conclusion

By understanding the nuances of <Link>, router.push, and the <a> tag, you can create a Next.js application with efficient, user-friendly, and SEO-optimized routing. Remember to choose the appropriate method based on your specific use case, leverage advanced techniques like dynamic routing and data fetching, and always consider accessibility and SEO best practices. With careful planning and implementation, you can ensure smooth and intuitive navigation that enhances the overall user experience of your Next.js application.

References

by Milton Berle Introduction Both Link and useRoutercan be used to navigating across routes in NextJS. My Recommended approach is useRouter . Let’s see how both works and why useRouter is be...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait