NextJS Link vs useRouter in Navigating.
Both Link
and useRouter
can be used to navigating across routes in NextJS. My Recommended approach is useRouter
. Let’s see how both works and why useRouter
is better than Link
Tag.
How does works:
First of all, Let’s see how does Link
tag work. If we use a
tag in our code.
function AnyName(){
return <a href="/next">Next Page</a>
}
If we click on a
tag, Then the browser fetch all files again which are even in Previous Page. So This may cause Lazy Loading. So NextJS makes this fetching faster.
import Link from "next/link";
function AnyName(){
return <Link href="/next">Next Page</ink>
}
If we click, Then it fetch only the file which is needed and It would not fetch files repeatedly.
If we inspect element, It would be like
<a href="/next">Next Page</a>
I think this would be enough about it, For more details go to Official docs .
Let’s see about useRouter
, It is just a React Hook, You can use to navigate by
import { useRouter } from 'next/router';function AnyName(){
const router = useRouter();
const navigate = ()=>{
router.push('/next');
}
return <button onClick={navigate}>Next Page</button>
}
Seems like confusing code. At this point, Link
is easier than useRouter
.Let’s see Why Link
is better than useRouter
. In Beginning, I felt Link
is better , but after using it, I found truth.
Why useRouter
is better
Currently Link
doesn’t support className
or style
, Styling is important for every website because User won’t use our code . They only see our UI. I always make my own Link
component using typescript,
import React from "react";
import { useRouter } from 'next/router';interface propType {
className: string;
to: string;
}const Link:React.FC<propType> = (props) => {
const router = useRouter();
const navigate= () =>{
router.push(props.to)
};
return (
<button
className={props.className}
onClick={navigate}>
{props.children}
</button>
}export default Link;
Conclusion
Choosing is based on your choice and your style. Here I shared my view.
Thank you for Reading.