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 using useRouter.

app/page.tsx
'use client';

// 'use client' marks this page as a Client Component
// https://beta.nextjs.org/docs/rendering/server-and-client-components

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:

  • The 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 from next/navigation and not next/router
  • The pathname string has been removed and is replaced by usePathname()
  • The query object has been removed and is replaced by useSearchParams()
  • router.events is not currently supported.

View the full migration guide.

Next Steps