Onjsdev

Share


How To Get Current Path In Next 13


By onjsdev

Nov 26th, 2023

In this article, we'll explore how to get the current path in next 13 using the usePathname hook.

Understanding usePathname

Let's begin by examining a simple example of how to use usePathname in a client component:

'use client'

import { usePathname } from 'next/navigation'

export default function MyComponent() {
  const pathname = usePathname()
  return <p>Current pathname: {pathname}</p>
}

In this code snippet, usePathname is utilized to retrieve the current URL's pathname. This information can then be used within the component for various purposes, such as rendering specific content based on the route.

How To Detect Changes In URL

To further illustrate the usage of usePathname, let's explore an example that responds to a route change:

'use client'

import { usePathname, useSearchParams } from 'next/navigation'

function MyComponent() {
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    // Do something here...
  }, [pathname, searchParams])
}

In this example, useEffect is employed to perform actions in response to changes in both the pathname and searchParams. This demonstrates how usePathname can be part of a solution that reacts to dynamic changes in the URL.

Conclusion

In conclusion, usePathname in Next.js 13 provides a straightforward yet powerful way to access the current URL's pathname within a client component

Thank you for reading.