reactjsreact-routernext.jsnext-routerreact-link

Typical differences between routers and links in NextJS


I am new to NextJS. I would like to know the typical variations and use cases between next/router and next/link.

Which one should I use in various scenarios? Which does what? For instance, if I want to load shared components or navigate among pages which are server-side rendered. Also what is the difference if I call a page with a normal 'a' tag or use a link/router to achieve the same.

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.pathname === href ? 'red' : 'black',
  }

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

export default ActiveLink

import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About Us</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home


Solution

  • what is the difference if I call a page with a normal 'a' tag or use a link/router to achieve the same?

    The main difference between a normal <a> tag and next/link or next/router is that the latter two are used for client-side transitions. So a normal <a> tag will load/navigate to the page with an http request, while router and link with load the page client-side.

    You can use next/router (inside a function in your component) when next/link is not enough, for example if you need to do some operations before render the new component.

    So both router and link has similar behaviours, you can choose, based on what your app needs to do, which one to use.

    Both, will run data fetching methods (getServerSideProps, getStaticProps, and getInitialProps)