DEV Community

Bradley Dirheimer
Bradley Dirheimer

Posted on

Next.js Navigation Hooks: A Deep Dive into useSelectedLayoutSegments

In the Next.js framework, managing navigation within your web applications can be simplified by using Client Component hooks. One such hook, useSelectedLayoutSegments, offers a unique capability in accessing the active route segments from the Layout where it's called, thus proving invaluable for creating complex UI elements such as breadcrumbs. This blog post will take an in-depth look at useSelectedLayoutSegments.

Understanding useSelectedLayoutSegments

useSelectedLayoutSegments is a Client Component hook designed to read active route segments, one level below the Layout it's called from. Here is a simple demonstration:

'use client'

import { useSelectedLayoutSegments } from 'next/navigation'

export default function ExampleClientComponent() {
  const segments = useSelectedLayoutSegments()

  return (
    <ul>
      {segments.map((segment, index) => (
        <li key={index}>{segment}</li>
      ))}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

This hook is typically invoked within a Client Component which is then imported into a Layout. This is because useSelectedLayoutSegments is a Client Component hook, while Layouts are Server Components by default.

The hook returns an array of strings representing active segments one level below from where the hook was called, or an empty array if none exist.

In situations where the returned segments include Route Groups (which you might not want to be included in your UI), you can leverage JavaScript's filter() array method to exclude items starting with a bracket.

useSelectedLayoutSegments does not accept any parameters. Here is how the return values look for different Layouts and URLs:

Layout Visited URL Returned Segments
app/layout.js / []
app/layout.js /dashboard ['dashboard']
app/layout.js /dashboard/settings ['dashboard', 'settings']
app/dashboard/layout.js /dashboard []
app/dashboard/layout.js /dashboard/settings ['settings']

Practical Use Case: Breadcrumbs

Breadcrumbs are a useful navigational aid in web interfaces. They allow users to understand their current location in relation to the site's hierarchy, providing a simple way to navigate back to previous levels.

In a Next.js application, you can leverage useSelectedLayoutSegments to generate breadcrumbs dynamically. For example, consider a site structure where a user navigates from Home > Blog > Article. You can create a breadcrumbs component using this hook as follows:

'use client'

import { useSelectedLayoutSegments } from 'next/navigation'
import Link from 'next/link'

export default function Breadcrumbs() {
  const segments = useSelectedLayoutSegments()

  return (
    <nav>
      <ul>
        {segments.map((segment, index) => (
          <li key={index}>
            <Link href={`/${segments.slice(0, index + 1).join('/')}`}>
              {segment}
            </Link>
          </li>
        ))}
      </ul>
    </nav>
  )
}
Enter fullscreen mode Exit fullscreen mode

In this example, the hook returns an array of active route segments. We then map through these segments to create a Link component for each, generating the href by slicing the segments array up to the current index and joining the slices with a slash.

In Conclusion

useSelectedLayoutSegments is a potent tool that comes bundled with the Next.js framework, granting you a way to enhance the UI and UX of your web applications. It simplifies the process of creating dynamic UI elements like breadcrumbs, providing users with a clearer view of their path within the website. Mastering this hook is a sure way to level up your Next.js development skills.

Top comments (0)