Link vs. router.push()
Next.js provides a Link component to navigate between the routes. It also provides the useRouter hook that has a method called push() using which you can navigate between the routes, too.
Then, which one to use? Let's understand the differences.
The Link Component
import Link from "next/link";
export default function Home() {
return <Link href="/about">About</Link>;
}
- It helps in navigating between routes.
- A direct replacement of the native anchor tag.
- Accessibility friendly.
- Can work without JavaScript.
- SEO friendly.
- Predictable prefetch/preloading capabilities.
The router.push() API
import { useRouter } from "next/navigation";
const router = useRouter();
const handleNavigation = () => {
router.push("/about"); // Navigate to the /about page
};
- Helps in navigation.
- Best for task-based routing/conditional routing.
- Only works inside the client components.
Next.js documentation recommends: "Use the Link component to navigate between the routes unless you have a specific requirement for using useRouter".
Want to learn further?
Check out the NextJS App Router series to learn Next.js with step-by-step approach with fundmental and code.
Full Stack with NextJS App Router - This series aims to teach you all the concepts of NextJS App router with fundamentals and hands-on practices. Along with clarifying the concepts, we will build the projects to solidify our understanding.