Capítulo 190 de 456

useSelectedLayoutSegment

Core Idea

Client Component hook that reads the active route segment one level below the Layout it's called from. Useful for navigation UI like tabs whose style depends on the active child segment.

Key Concepts

  • useSelectedLayoutSegment(parallelRouteKey?): Retorna string do segmento ativo ou null; aceita opcionalmente uma chave de parallel route.
  • Catch-all segments: São retornados como uma única string unida (ex. 'a/b/c'), não um array.

Code Examples

'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'

export default function BlogNavLink({ slug, children }: { slug: string; children: React.ReactNode }) {
  const segment = useSelectedLayoutSegment()
  const isActive = slug === segment
  return (
    <Link href={`/blog/${slug}`} style={{ fontWeight: isActive ? 'bold' : 'normal' }}>
      {children}
    </Link>
  )
}
  • O que demonstra: Componente cliente importado num layout de servidor pra destacar o link ativo comparando com o segmento retornado.

Reference Tables

LayoutVisited URLReturned 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/monthly'analytics'
app/blog/layout.js/blog/a/b/c (catch-all)'a/b/c'

Anti-patterns

  • Chamar diretamente num Layout Server Component: o hook exige 'use client'; deve ser chamado num componente cliente separado importado pelo layout.

Key Takeaways

  1. Só retorna o segmento um nível abaixo; para todos os níveis use useSelectedLayoutSegments.
  2. Com cacheComponents ativo, rotas com params dinâmicos não cobertos por generateStaticParams fazem o hook suspender, exigindo Suspense.
  3. Um tab bar estático ainda suspende se qualquer página abaixo tiver param dinâmico desconhecido — envolva o componente (ou um pai) em Suspense.

Connects To

  • useSelectedLayoutSegments: variante que retorna todos os segmentos ativos, não só um nível.
  • parallel-routes: onde parallelRouteKey é relevante.