When working with Next.js 13+ (App Router), we no longer rely on the old next/router. Instead, Next.js provides a new set of navigation hooks inside the next/navigation package. These hooks make it easier to handle routing, query parameters, and pathnames in a React-friendly way.
In this blog, weβll learn how to use the following hooks:
useRouteruseParamsuseSearchParamsusePathname
π Importing Navigation Hooks
You start by importing the hooks from next/navigation:
'use client';
import {
useRouter,
useParams,
useSearchParams,
usePathname,
} from 'next/navigation';
π Notice the 'use client' directive β these hooks only work in client components, not server components.
π Example: Using Navigation Hooks in a Component
Hereβs a simple component that demonstrates how to use all four hooks:
const PropertyPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const id = useParams();
const name = searchParams.get('name');
const pathname = usePathname();
return (
<div>
<h1>Property Page</h1>
<p>Property ID: {id?.propertyId}</p>
<p>Name: {name}</p>
<p>Current Path: {pathname}</p>
<button onClick={() => router.push('/')}>Go Home</button>
</div>
);
};
π Hook-by-Hook Explanation
1. useRouter()
- Works similar to
next/routerfrom older versions. - Lets you navigate programmatically (
push,replace,back). - Example:
router.push('/dashboard');
2. useParams()
- Returns dynamic route parameters from the URL.
- Example: For
/property/123,useParams()will return:{ propertyId: "123" }
3. useSearchParams()
- Used to get query parameters (
?name=John). - Example:
const searchParams = useSearchParams(); const name = searchParams.get('name'); // "John"
4. usePathname()
- Returns the current URL path.
- Example: For
/property/123?name=John, it will return:"/property/123"
β When to Use These Hooks
useRouterβ when you need navigation actions.useParamsβ when working with dynamic routes.useSearchParamsβ when working with query strings.usePathnameβ when you just need the current path.
π― Conclusion
The new Next.js App Router hooks make routing cleaner and easier to manage. Instead of juggling different APIs, you now have a simple, unified way to handle URLs, paths, and query parameters.
π Next time you build a page in Next.js 13+, try using these hooks to simplify your navigation logic.
