useRouter
The useRouter
hook allows you to programmatically change routes inside Client Components.
Recommendation: Use the
<Link>
component for navigation unless you have a specific requirement for usinguseRouter
.
'use client';
import { useRouter } from 'next/navigation';
export default function Page() {
const router = useRouter();
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
);
}
useRouter()
router.push(href: string)
: Perform a client-side navigation to the provided route. Adds a new entry into the browser’s history stack.router.replace(href: string)
: Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack.router.refresh()
: Refresh the current route and fetch new data from the server. This does not reset state like scroll position or forms, for example.router.prefetch(href: string)
: Prefetch the provided route for faster client-side transitions.router.back()
: Navigate back to the previous route in the browser’s history stack using soft navigation.router.forward()
: Navigate forwards to the next page in the browser’s history stack using soft navigation.Good to know:
push()
and replace()
methods will perform a soft navigation if the new route has been prefetched, and either, doesn't include dynamic segments or has the same dynamic parameters as the current route.next/link
automatically prefetch routes as they become visible in the viewport.Migrating from the
pages
directory:
- The new
useRouter
hook should be imported fromnext/navigation
and notnext/router
- The
pathname
string has been removed and is replaced byusePathname()
- The
query
object has been removed and is replaced byuseSearchParams()
router.events
is not currently supported.