Topic 30 of 47
useRouter Hook
Overview
Sometimes you need to navigate the user dynamically (e.g., after a form submission). In the App Router, the `useRouter` hook is imported from `next/navigation` and can only be used inside Client Components.
Syntax
tsx
// app/login/page.tsx
'use client';
import { useRouter } from 'next/navigation';
export default function Login() {
const router = useRouter();
const handleLogin = async () => {
// 1. Perform login logic
await authenticateUser();
// 2. Programmatically redirect to dashboard
router.push('/dashboard');
};
return <button onClick={handleLogin}>Log In</button>;
}Common Pitfalls
- Ensure you import `useRouter` from `next/navigation`, NOT `next/router`. The latter is for the old Pages Router and will throw an error.
- You cannot use `useRouter` in a Server Component. If you need to redirect from the server, use the `redirect()` function from `next/navigation`.
Real-World Example
Using useRouter methods in a Client Component:
example
tsx
const router = useRouter();
// Navigate to a new route
router.push('/dashboard');
// Replace current route (no history entry)
router.replace('/dashboard');
// Refresh the current route (re-fetches Server Components without losing client state)
router.refresh();
// Go back
router.back();
// Go forward
router.forward();