useSelectedLayoutSegment

The useSelectedLayoutSegment hook allows you to read the active route segment one level down from a layout. It is useful for navigation UI such as tabs that change style depending on which segment is active.

app/ExampleClientComponent.tsx
'use client';

import { useSelectedLayoutSegment } from 'next/navigation';

export default function ExampleClientComponent() {
  const segment = useSelectedLayoutSegment();

  return <>Active segment: {segment}</>;
}

useSelectedLayoutSegment is a hook that can only be used inside a Client Component. You can use it in a client component that is imported into a layout. It returns a string of the active segment or null if one doesn't exist.

Examples

LayoutURLSelected Segment
app/layout.js/null
app/layout.js/dashboard'dashboard'
app/dashboard/layout.js/dashboardnull
app/dashboard/layout.js/dashboard/settings'settings'
app/dashboard/layout.js/dashboard/analytics'analytics'
app/dashboard/layout.js/dashboard/analytics/monthly'analytics'

You can use useSelectedLayoutSegment to create an active link component that changes style depending on which segment is active. For example, a featured posts list in the sidebar of a blog:

app/blog/BlogNavLink.tsx
'use client';

import Link from 'next/link';
import { useSelectedLayoutSegment } from 'next/navigation';

// This *client* component will be imported into a blog layout
export default function BlogNavLink({
  slug,
  children,
}: {
  slug: string,
  children: React.ReactNode,
}) {
  // Navigating to `/blog/hello` will return 'hello' for the
  // selected layout segment
  const segment = useSelectedLayoutSegment();
  const isActive = slug === segment;

  return (
    <Link
      href={`/blog/${slug}`}
      // Change style depending on whether the link is active
      style={{ fontWeight: isActive ? 'bold' : 'normal' }}
    >
      {children}
    </Link>
  );
}
app/blog/layout.tsx
import { BlogNavLink } from './BlogNavLink';
import getFeaturedPosts from './getFeaturedPosts';

export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  const fearturedPosts = await getFeaturedPosts();
  return (
    <div>
      {fearturedPosts.map((post) => (
        <div key={post.id}>
          <BlogNavLink slug={post.slug}>{post.title}</BlogNavLink>
        </div>
      ))}
      <div>{children}</div>
    </div>
  );
}