How to Use useRouter in Next.js for Navigation and Routing
In Next.js, you use the
useRouter hook from next/router to access the router object inside functional components. This lets you read the current URL, query parameters, and navigate programmatically with methods like push and replace.Syntax
The useRouter hook is imported from next/router and returns the router object. You use it inside a React functional component to get routing info and navigation methods.
const router = useRouter();— gets the router object.router.push(url)— navigates to a new URL.router.query— contains URL query parameters.
javascript
import { useRouter } from 'next/router'; function MyComponent() { const router = useRouter(); // Access current path console.log(router.pathname); // Navigate to /about function goToAbout() { router.push('/about'); } return null; }
Example
This example shows a button that navigates to a dynamic user page using useRouter. It also displays the current query parameter from the URL.
javascript
import { useRouter } from 'next/router'; export default function UserProfile() { const router = useRouter(); const { id } = router.query; // get dynamic route param function goHome() { router.push('/'); } return ( <div> <h1>User Profile</h1> <p>User ID from URL: {id}</p> <button onClick={goHome}>Go Home</button> </div> ); }
Output
<h1>User Profile</h1>
<p>User ID from URL: 123</p>
<button>Go Home</button>
Common Pitfalls
- Using
useRouteroutside components: It only works inside React functional components, not in regular functions or class components. - Accessing
router.querytoo early: On first render, query params may be empty because Next.js fetches them asynchronously. - Forgetting to import
useRouter: Always import it fromnext/router.
javascript
/* Wrong: Using useRouter outside component */ import { useRouter } from 'next/router'; // const router = useRouter(); // ❌ This causes error function Page() { return <div>Page</div>; } /* Right: Use inside component */ function PageCorrect() { const router = useRouter(); // ✅ Correct return <div>Page</div>; }
Quick Reference
Here is a quick summary of common useRouter properties and methods:
| Property/Method | Description |
|---|---|
| router.pathname | Current route path without query string |
| router.query | Object with URL query parameters |
| router.push(url) | Navigate to a new URL, adds to history |
| router.replace(url) | Navigate to a new URL, replaces current history entry |
| router.back() | Go back to previous page |
| router.reload() | Reload the current page |
Key Takeaways
Use
useRouter inside functional components to access routing info and navigation.Access
router.query carefully as it may be empty on first render.Use
router.push or router.replace to navigate programmatically.Never call
useRouter outside React components.Remember to import
useRouter from next/router.