Programmatic navigation lets your app change pages by code, not just by clicking links. This helps make your app interactive and dynamic.
Programmatic navigation (useRouter) in 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.
'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>; }
'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>; }
'use client'; import { useRouter } from 'next/navigation'; export default function BackButton() { const router = useRouter(); return <button onClick={() => router.back()}>Go Back</button>; }
This component shows a contact form. When the user submits it, the page changes to '/thank-you' using programmatic navigation.
'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> ); }
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.
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.
Practice
useRouter hook from next/navigation allow you to do in a Next.js app?Solution
Step 1: Understand the purpose of useRouter
TheuseRouterhook provides methods to change pages in code, not by user clicking links.Step 2: Identify what useRouter does not do
It does not handle data fetching, styling, or auto-reloading pages.Final Answer:
Navigate between pages programmatically using code -> Option AQuick Check:
useRouter = programmatic navigation [OK]
- Confusing useRouter with data fetching hooks
- Thinking useRouter styles components
- Assuming useRouter reloads pages automatically
useRouter from Next.js 14+ for programmatic navigation?Solution
Step 1: Recall the correct import path for useRouter in Next.js 14+
In Next.js 14+,useRouteris imported fromnext/navigation, notnext/router.Step 2: Check syntax correctness
import { useRouter } from 'next/navigation'; uses named import from the correct module. import useRouter from 'next/navigation'; misses braces, causing syntax error. import { useRouter } from 'next/navigation/useRouter'; uses a wrong path.Final Answer:
import { useRouter } from 'next/navigation'; -> Option AQuick Check:
Correct import = import { useRouter } from 'next/navigation'; [OK]
- Importing from 'next/router' instead of 'next/navigation'
- Missing curly braces in import
- Using incorrect import paths
import { useRouter } from 'next/navigation';
export default function Home() {
const router = useRouter();
return (
<button onClick={() => router.push('/about')}>Go to About</button>
);
}Solution
Step 1: Understand router.push behavior
Therouter.push('/about')method navigates to the '/about' page and adds a new entry in the browser history stack.Step 2: Confirm the code triggers navigation on button click
The button's onClick calls router.push correctly, so navigation happens as expected.Final Answer:
The page will navigate to '/about' adding a new entry in browser history -> Option CQuick Check:
router.push adds history entry = The page will navigate to '/about' adding a new entry in browser history [OK]
- Confusing router.push with router.replace
- Thinking router.push reloads current page
- Assuming router.push does nothing without await
useRouter for navigation:import { useRouter } from 'next/navigation';
export default function Page() {
const router = useRouter;
return (
<button onClick={() => router.push('/contact')}>Contact</button>
);
}Solution
Step 1: Check how useRouter is assigned
The code assignsconst router = useRouter;without calling it as a function. It should beuseRouter().Step 2: Verify other parts
router.push is valid for navigation. onClick syntax is correct. Import path is correct.Final Answer:
Missing parentheses when calling useRouter hook -> Option DQuick Check:
useRouter must be called as a function [OK]
- Assigning useRouter without parentheses
- Using router.push incorrectly in onClick
- Importing useRouter from wrong module
useRouter should you use and how?const router = useRouter(); // Your code here
Solution
Step 1: Understand difference between push and replace
router.push()adds a new entry to browser history, whilerouter.replace()swaps the current entry.Step 2: Choose method to avoid adding history entry
To navigate without adding a new history entry, userouter.replace('/newpage').Final Answer:
Use router.replace('/newpage') to replace current history entry -> Option BQuick Check:
replace swaps history entry = Userouter.replace('/newpage')to replace current history entry [OK]
- Using router.push when replace is needed
- Confusing reload with navigation
- Using router.back instead of forward navigation
Ready to prove it?
Pass the test and this pattern moves unknown
