I'm newbie with just a basic knowledge of next js. I discovered userouter() from next/navigation. I have a question that why we should use router.push when we can use Link?
A example explaining why we should use router.push() instead of Link?
You can use the router.push
function to navigate programmatically inside of client component. Let's assume you want to navigate a user to another page under the condition that a specific requirement is met, this is a suitable use case for router.push
. See an example usage below:
const cartTotalAmount = 200;
const onCheckoutHandler = () => {
if(cartTotalAmount >= 150) {
return router.push("/checkout")
}
alert("You need to have up to 50USD in your cart to checkout")
}
From the example above, I am allowing a user to go to the checkout route only if the amount in the cart is greater than or equal to 150. In essence, I am programmatically allowing the user to go to the /checkout
page only if the set condition is. The router.push
function can also be used to navigate user to specific route after form submission. For example, if you want the user to be navigated to the /dashboard
route after a successful authentication.
However, the Link
component works like the native <a></a>
anchor tag but optimized for client and server-side navigation. It's the recommended way to navigate to different routes especially if the destination is known ahead of time. It's also optimized for prefetching routes ahead of time for better performance and faster navigation to different routes. It also handles accessibility concerns so screen readers get to be aware they are about to navigate to a specific destination.
The NextJS docs recommends using the Link
component except you have a specific reason for using the useRouter
hook: https://nextjs.org/docs/app/api-reference/functions/use-router#userouter