Programmatic Routing
In most cases, the <Link>
component is the best way to get folks from one page to another. Users are familiar with hyperlinks, after all!
Occasionally, however, we might wish to bring the user to a new page programmatically. For example, maybe they submit a contact form, and we want to take them back to the homepage:
For programmatic navigation, we can use the useRouter
custom hook:
'use client';import React from 'react';import { useRouter } from 'next/navigation';
function ContactPage() { const router = useRouter();
function handleSubmit(event) { event.preventDefault();
// ✂️ Send data to server
router.push('/'); }
return ( <form onSubmit={handleSubmit}> {/* ✂️ Form stuff here */} </form> );}
We call router.push
with a new URL — in this case, we're taking them back to the homepage. This is equivalent to them clicking a <Link>
tag — it uses the same optimized transition, no need to download a new HTML file.
It's called “push” because it pushes the new URL onto the history stack; after the transition, the user can use the browser's “back” button to go back to the contact page.
For more information on all the cool programmatic-routing stuff we can do in Next, check out the official docs (opens in new tab).