Programmatic Routing
Part of the Next.js Essentials section of Coddy's React journey — lesson 35 of 47.
<Link> covers navigation the user chooses. But sometimes the app decides: after a form submits, after a login succeeds, after a button click that has work to do first.
For those, you navigate from code with useRouter:
'use client';
import { useRouter } from 'next/navigation';
export default function CheckoutButton() {
const router = useRouter();
return (
<button onClick={() => router.push('/thanks')}>
Check out
</button>
);
}The router object gives you:
router.push(url): go there, and add it to historyrouter.replace(url): go there, replacing the current entry (no going back to it)router.back(): one step backwardsrouter.refresh(): re-run the server render of the current route
Two rules worth remembering. First, useRouter comes from next/navigation, not the old next/router. Second, it's a hook, so it needs 'use client'.
When a plain link would do, use a link: it's a real <a>, so it works with keyboards, screen readers and middle-click. Reach for router.push when the navigation is a consequence of something, not the thing itself.
Challenge
EasyThe home page has an "Order now" button that does nothing. Make it navigate.
- In
components/OrderButton.jsx, get the router withuseRouter(). - On click, send the user to
/menuwithrouter.push.
Leave the button's id="order-btn" alone: the tests click it.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
4Server & Client
Two Kinds of ComponentReading the ErrorThe 'use client' LineKeep Client Parts SmallServer Inside ClientRecap: Server & Client7Client Navigation
The Active LinkProgrammatic RoutingFiltering with the URLRoute HandlersRecap: Navigation