DEV Community

Rishabh Jain
Rishabh Jain

Posted on

When to use Link tag and useRouter hook in nextjs??

Kindaa confuse in usage of both and i am using both of them in redirecting. 😬

Top comments (2)

Collapse
 
sakko profile image
SaKKo

I guess the easy answer is
Use <Link href="" passHref> when you can define the destination in JSX.

And use useRouter when you want to programmatically redirect using javascript.
eg. instead of using window.location = "" use router.push("")

Collapse
 
gian412 profile image
gian.regis

Hi @rishabh0906, I'll try to answer your question, but before that, let me say some useful information.

<Link> tags are the best option if they can be used, as they have a bunch of nice features like prefetching the page when the link is in the viewport.

As per your question, <Link> tags have to be used every time you would put a link on a page (e.g. with an <a> tag), while router.push() have to be used whenever a <Link> tag can't, for example, if you have to redirect the user after some complex logic.

Example

An example of link usage:

<div>
Find more about us in the <Link href='/about'><a>about page</a></Link>
</div>
Enter fullscreen mode Exit fullscreen mode

An example of useRouter usage:

import { useState } from 'react';
import { useRouter } from 'next/router';


const MyComponent = () => {
    const router = useRouter();
    const [error,  setError] = useState('');

    const complex_logic_to_be_checked = () => {
        // ....
    } 

    const handleClick = () => {
        const ok = complex_logic_to_be_checked();

        if (!ok) {
            setError('Check failed');
        }

        router.push('/success');
    }

    return (
        <h1>Edit the data<h1>
        {error.length > 0 && (
            <div>Error: {error}</div>
        }

        <input />

        <button onClick={handleClick}>Save</button>
    );
}


Enter fullscreen mode Exit fullscreen mode
Caveats

The <Link> tag has to be used only for internal navigation. if you have to redirect the user to an external page, simply use an <a> tag.