Programmatic Navigation
Navigate from code using the useRouter hook in Client Components.
Syntax
const router = useRouter(); router.push('/path');Sometimes you need to navigate in response to logic — after a form submit, a timeout, or a button click. Use the useRouter hook from next/navigation. Because hooks only run in the browser, the component must be a Client Component ("use client").
Common router methods
router.push('/path')— navigate to a new route.router.replace('/path')— navigate without adding a history entry.router.back()— go to the previous page.router.refresh()— re-fetch the current route's server data.
Example
'use client';
import { useRouter } from 'next/navigation';
export default function LoginButton() {
const router = useRouter();
return (
<button onClick={() => router.push('/dashboard')}>
Go to dashboard
</button>
);
}When to use it
- After a successful form submission a handler calls router.push('/dashboard') to redirect the user.
- A search component calls router.push with an updated query string when the user changes filter options.
- A logout function calls router.replace('/login') so the dashboard is removed from the browser history.
More examples
Push to new route on submit
router.push navigates programmatically and adds an entry to the browser history stack.
'use client';
import { useRouter } from 'next/navigation';
export default function LoginForm() {
const router = useRouter();
function handleSubmit() {
// ... authenticate
router.push('/dashboard');
}
return <button onClick={handleSubmit}>Log in</button>;
}Replace history on logout
router.replace redirects without adding to history, so back button skips the protected page.
'use client';
import { useRouter } from 'next/navigation';
export default function LogoutButton() {
const router = useRouter();
return (
<button onClick={() => router.replace('/login')}>
Log out
</button>
);
}Refresh server data in place
router.refresh re-runs Server Components in the current route without a full page reload.
'use client';
import { useRouter } from 'next/navigation';
export default function RefreshButton() {
const router = useRouter();
return (
<button onClick={() => router.refresh()}>
Reload data
</button>
);
}
Discussion