useRouter is a Client Component hook that lets you programmatically change routes.
app/example-client-component.tsx
Methods
Navigates to the given route and adds a new entry to the browser history stack.Options:
scroll?: boolean— Whether to scroll to the top after navigation (default:true).transitionTypes?: string[]— Passed toReact.addTransitionTypeinside the navigation Transition.
Navigates to the given route without adding a new history entry (replaces the current one).Options: same as
push.Refreshes the current route by making a new request to the server. Re-fetches data and re-renders Server Components. The client merges the result without losing unaffected React state or browser state (e.g. scroll position).This clears the Client Cache for the current route. To also invalidate server-side cache, use
revalidatePath or revalidateTag.Prefetches the route for faster client-side transitions.Options:
onInvalidate?: () => void— Called when the prefetched data becomes stale.
Navigates back to the previous entry in the browser history stack.
Navigates forward to the next entry in the browser history stack.
Good to know
- Do not pass untrusted or unsanitized URLs to
router.pushorrouter.replace. Passingjavascript:URLs can execute arbitrary code in your page (XSS). refresh()may produce the same result iffetchrequests are still cached. Other Request-time APIs likecookiesandheaderscan also affect the response.- The
onInvalidatecallback is called at most once per prefetch request.
Examples
Disabling scroll to top
app/example.tsx
Listening for route changes
ComposeusePathname and useSearchParams to react to route changes:
app/components/navigation-events.tsx
Suspense boundary when used in a layout, since useSearchParams suspends during prerendering:
app/layout.tsx
Migrating from next/router
Old (next/router) | New (next/navigation) |
|---|---|
useRouter() | useRouter() |
router.pathname | usePathname() |
router.query | useSearchParams() |
router.events | Compose usePathname + useSearchParams |
Version history
| Version | Changes |
|---|---|
v15.4.0 | Optional onInvalidate callback for router.prefetch introduced. |
v13.0.0 | useRouter from next/navigation introduced. |
