How to use Next.js router

Learn how to usenext/routerPackage to control routing in Next.js

inUse links to link two pages in Next.jsWe saw how to use the Link component to declaratively handle routing in the Next.js application.

It is really convenient to manage routing in JSX, but sometimes you need to trigger routing changes programmatically.

In this case, you can directly access the Next.js router (innext/routerPackage and then call itpush()method.

This is an example of accessing the router:

import { useRouter } from 'next/router'

export default () => { const router = useRouter() //… }

Once the router object is obtained by callinguseRouter(), We can use its method.

This is a client router, so the method should only be used in front-end-facing code. The easiest way to ensure this is to wrap the call inuseEffect()Reaction hook or internalcomponendDidMount()In React stateful components.

What you use most often ispush()withprefetch().

push()Allow us to trigger URL changes programmatically on the front end:

router.push('/login')

prefetch()Allows us to prefetch URLs programmatically, useful when we don’t have a URLLinkThe label will automatically handle prefetching for us:

router.prefetch('/login')

Full example:

import { useRouter } from 'next/router'

export default () => { const router = useRouter()

useEffect(() => { router.prefetch(’/login’) }) }

You can also use the router to listenRoute change event.

Download mine for freeNext.js manual


More tutorials next: