DEV Community

Noah
Noah

Posted on

Difference between router.push, <Link> and <a> in Next.js

Here’s a brief overview of the differences in behavior among the three.

router.push

explanation about router.push component in next.js

router.push doesn't generate <a> tags, so its behavior is similar to window.location. This means that if you're concerned about SEO, your links might not be detected by crawlers.

router.push is mostly used in an event handler (onClick here). This is an action. So let's say you click on the button, then you do some task, and based on the result you take the user to another page. Then you'd want to use router.push

<Link>

explanation about <Link> component in next.js

On the other hand, <Link> generate <a> tags. which means your links will be detected when crawlers scrape your site.
End users can still navigate without reloading the page, just like in a Single Page App.

The <Link> component also includes prefetching.
This means all pages linked to by any <Link> in the viewport or hovered on are loaded in advance, ready to be displayed when clicked on.

<a>

explanation about <a> component in next.js

<a> tag without using next/link's <Link> creates a standard hyperlink which directs end user to the url as a new page. (standard behavior).

Conclusion

router.push:

Used for programmatic navigation, similar to window.location, and doesn't generate <a> tags, so it might not be SEO-friendly.

<Link>:

Generates <a> tags, making it SEO-friendly and supports prefetching for better performance in Single Page Applications.

<a>:

Standard HTML hyperlink, reloads the page entirely and doesn't leverage Next.js routing optimizations.

You should use <Link> throughout your website.
However, if you need to redirect users to another page based on the result of a process, you can use router.push.

Happy Coding☀️

Top comments (0)