NextJS Link vs useRouter in Navigating.

If opportunity doesn't knock your door , build a door.
by Milton Berle
Introduction
Both Link and useRoutercan 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 by Link tag, Let's see example,
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 you find in 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;
style: React.CSSProperties;
}
const Link:React.FC<propType> = (props) => {
const router = useRouter();
const navigate= () =>{
router.push(props.to)
};
return (
<button
className={props.className}
onClick={navigate}>
style={ props.style || { } }
{props.children}
</button>
}
export default Link;
You can also create Custom Components with Link,
import React from "react";
import Link from 'next/link';
interface propType {
className: string;
to: string;
style: React.CSSProperties;
}
const Link: React.FC<propType> = ( props ) => {
return (
<Link to={props.} >
<span
className={ props.className }
style={ props.style || { } } >
{ props.children }
</span>
</Link>
)
}
export default Link;
But You can't make your own ActiveLinklike Components without useRouter,
Conclusion
Choosing is based on your choice and your style. Here I shared my view.