Struggling with Active Links in Next.js? This Hook Solves It!
Tired of writing complex logic to highlight active navigation links in Next.js? Say hello to useIsActivePath
—a simple yet powerful custom hook that handles all edge cases for you!
The Problem with Active Links in Next.js
Manually checking pathname
for active states gets messy:
- Exact paths (
/about
) - Dynamic routes (
/blog/[slug]
) - Relative paths (
about
vs/about
) - Wildcard matching (
/docs*
for nested routes)
Most solutions require repetitive code — but not anymore!
The Solution: useIsActivePath
Hook
This tiny hook does all the heavy lifting:
import useIsActivePath from "./useIsActivePath";
const NavItem = ({ path, label }) => {
const isActive = useIsActivePath(path);
return <Link href={path} className={isActive ? "text-blue-500" : ""}>{label}</Link>;
};
Key Features
✔ Exact matches (/dashboard
)
✔ Relative paths (dashboard
→ /dashboard
)
✔ Wildcard support (/blog*
matches /blog/123
)
✔ No more manual string checks!
Why This Hook is a Game-Changer
✅ Cleaner code — No more repetitive pathname
checks
✅ Flexible matching – Supports all common routing patterns
✅ Reusable – Drop it into any navigation component
Try It Out!
import { usePathname } from "next/navigation";
const useIsActivePath = (path: string): boolean => {
const pathname = usePathname();
if (path.endsWith("*")) {
path = path.slice(0, -1);
return pathname.startsWith(path) || pathname === path;
}
return pathname === path || pathname.slice(1) === path;
};
Like this tip? Follow me for more Next.js & React insights! 🚀
#NextJS #WebDev #Frontend #ReactHooks #Programming
Comments
Post a Comment