useRouter: Programmatic Navigation in Next.js
The useRouter hook gives you a router object to programmatically control navigation. Use it for event-driven redirects, like sending a user to their dashboard after a successful login.
WHY IT EXISTS: Applications often need to change routes based on logic, not just a user clicking a link. Scenarios like redirecting after a successful API call, completing a form submission, or enforcing authentication require a way to trigger navigation from within your code. The useRouter hook provides this imperative API.
THE MENTAL MODEL: Think of the <Link> component as a static signpost telling users where they can go. In contrast, useRouter is like a GPS navigator that can actively reroute you based on real-time events and conditions. It's for when the application decides to navigate, not just the user.
HOW IT WORKS: When you call const router = useRouter() in a Client Component, Next.js provides an object with methods for navigation. The most common is router.push('/dashboard'), which adds a new entry to the browser's history stack and navigates to the new page. Other methods include router.replace() (navigates without adding to history), router.back() (goes to the previous page), and router.refresh() (re-fetches data for the current route).
WHEN TO USE IT: Use useRouter for navigation triggered by functions or event handlers. A classic example is a login form: upon successful authentication, you call router.push('/profile') inside your submit handler. It's also ideal for multi-step wizards or redirecting users away from protected pages if they aren't authenticated.
WHEN NOT TO USE IT: For standard, static navigation where a user clicks a visible link, always prefer the <Link> component. <Link> is more accessible, crawlable by search engines, and handles performance optimizations like prefetching automatically. Using useRouter with an onClick on a generic is an anti-pattern that recreates a link with worse performance and accessibility.
ONE CANONICAL EXAMPLE: A login component that redirects on success. Inside its form submission handler, after successfully validating the user's credentials with an API, you would call router.push('/dashboard'). This programmatically sends the user to their main application page, happening within a function rather than as a direct result of clicking a static link.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.