Programmatic navigation lets your app change pages by code, not just by clicking links. This helps make your app interactive and dynamic.
0
0
Programmatic navigation (useRouter) in NextJS
Introduction
After a user submits a form, send them to a confirmation page.
Redirect users to login if they try to access a protected page.
Move to a different page after a button click without a link.
Navigate based on some condition or result in your code.
Syntax
NextJS
'use client'; import { useRouter } from 'next/navigation'; export default function Component() { const router = useRouter(); // To navigate to a new page router.push('/path'); // To replace current page (no back) router.replace('/path'); // To go back router.back(); }
Use useRouter from next/navigation in Next.js 13+ App Router.
router.push() adds a new entry in browser history, router.replace() replaces current entry.
Examples
Navigate to '/about' page when button is clicked.
NextJS
'use client'; import { useRouter } from 'next/navigation'; export default function Home() { const router = useRouter(); function goToAbout() { router.push('/about'); } return <button onClick={goToAbout}>Go to About</button>; }
After login, replace current page with '/dashboard' so user can't go back to login.
NextJS
'use client'; import { useRouter } from 'next/navigation'; export default function Login() { const router = useRouter(); async function handleLogin() { // pretend login success router.replace('/dashboard'); } return <button onClick={handleLogin}>Login</button>; }
Go back to previous page in browser history.
NextJS
'use client'; import { useRouter } from 'next/navigation'; export default function BackButton() { const router = useRouter(); return <button onClick={() => router.back()}>Go Back</button>; }
Sample Program
This component shows a contact form. When the user submits it, the page changes to '/thank-you' using programmatic navigation.
NextJS
'use client'; import React from 'react'; import { useRouter } from 'next/navigation'; export default function Contact() { const router = useRouter(); function handleSubmit(event) { event.preventDefault(); // After form submission, navigate to thank you page router.push('/thank-you'); } return ( <main> <h1>Contact Us</h1> <form onSubmit={handleSubmit} aria-label="Contact form"> <label htmlFor="name">Name:</label> <input id="name" name="name" type="text" required /> <label htmlFor="message">Message:</label> <textarea id="message" name="message" required></textarea> <button type="submit">Send</button> </form> </main> ); }
OutputSuccess
Important Notes
Programmatic navigation works only inside client components in Next.js App Router.
Always use semantic HTML and ARIA labels for accessibility when building interactive elements.
Summary
useRouter from next/navigation lets you change pages by code.
Use router.push() to add a new page, router.replace() to swap current page.
Programmatic navigation helps make apps interactive and user-friendly.