Menu
Coddy logo textTech

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 history
  • router.replace(url): go there, replacing the current entry (no going back to it)
  • router.back(): one step backwards
  • router.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 icon

Challenge

Easy

The home page has an "Order now" button that does nothing. Make it navigate.

  1. In components/OrderButton.jsx, get the router with useRouter().
  2. On click, send the user to /menu with router.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>
    );
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Next.js Essentials