How does useRouter work in app router?
useRouter in the App Router (Next.js 13+) is a client navigation hook that lets you control transitions and history without reloading the page.
Important right away:
useRouterworks only in Client Components and is imported fromnext/navigation.
Where it comes from and where to use it
In the Next.js App Router:
'use client'
import { useRouter } from 'next/navigation'- needs
'use client' - cannot be used in Server Components
What useRouter does
1. Navigation between pages
router.push('/blog')
router.replace('/login')push- adds an entry to historyreplace- replaces the current entry (no Back)
2. Going back / forward
router.back()
router.forward()3. Refreshing the current route
router.refresh()- re-requests Server Components
- re-runs
fetchon the server - useful after a
Server Action
What useRouter does not do in the App Router
This is a common trap in interviews.
- does not read params
- does not read search params
- does not know the current pathname
For that there are other hooks:
useParams() // route params
useSearchParams() // ?query=1
usePathname() // /blog/postDifference from Pages Router
| Pages Router | App Router |
|---|---|
next/router | next/navigation |
| router.query | none |
| one hook | several specialized ones |
In the App Router there is separation of responsibility.
A typical case
'use client'
import { useRouter } from 'next/navigation'
export function LogoutButton() {
const router = useRouter()
async function logout() {
await signOut()
router.replace('/login')
router.refresh()
}
return <button onClick={logout}>Logout</button>
}When to use useRouter
-
navigation on an event (submit, click)
-
a redirect after an action
-
refreshing data after a mutation
-
managing history
-
not for rendering
-
not for SEO
-
not for fetching data
Short answer for an interview
useRouterin the App Router is a client navigation hook fromnext/navigation, which lets you programmatically control transitions, history, and route refresh, but it is not meant for reading URL parameters.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.