Capítulo 52 de 57

Chapter 52: Static Route Data

Core Idea

The staticData route option lets you attach arbitrary, synchronously-available metadata to a route at definition time, accessible both from the route itself and from any match.staticData at runtime, ideal for layout flags, breadcrumb titles, and other data that doesn't depend on params, context, or async loading.

Key Concepts

  • staticData: A free-form object set in createFileRoute(...)({ staticData: {...} }), available synchronously as soon as the route is defined, no loader or context required.
  • Access via matches: useMatches() returns matched routes, each exposing .staticData, letting a root layout aggregate metadata across the whole matched hierarchy.
  • StaticDataRouteOption declaration merging: Augmenting this interface (declare module '@tanstack/react-router' { interface StaticDataRouteOption { customData: string } }) enforces that every route must supply the given static data (TypeScript errors otherwise); making the property optional (customData?: string) relaxes the requirement.
  • staticData vs context: staticData is synchronous, fixed at route definition, and identical for all instances of a route; context can be async (via beforeLoad), depend on params/search, and passes down to children. Use staticData for static metadata, context for dynamic/auth-dependent data.
  • Common patterns: Controlling layout visibility (e.g. staticData: { showNavbar: false } read in the root layout to conditionally wrap children), and generating breadcrumb titles (staticData: { getTitle: () => 'Post Details' } read via useMatches in a Breadcrumbs component).

Code Examples

export const Route = createFileRoute('/posts')({
  staticData: {
    customData: 'Hello!',
  },
})
export const Route = createRootRoute({
  component: () => {
    const matches = useMatches()
    return (
      <div>
        {matches.map((match) => (
          <div key={match.id}>{match.staticData.customData}</div>
        ))}
      </div>
    )
  },
})
  • What it demonstrates: Defining static data on a route and reading it back from any matched route in a shared layout component.

Key Takeaways

  1. Use staticData for metadata that's fixed and synchronous (layout flags, titles, icons); use context/beforeLoad when the value must be computed asynchronously or depends on params/auth state.
  2. Enforce required static data project-wide via StaticDataRouteOption declaration merging, catching routes that forgot to set it at compile time.
  3. useMatches() combined with staticData is the standard pattern for breadcrumbs, conditional layout chrome, and per-page title tags.

Connects To

  • Ch 49: Router Context, the dynamic/async counterpart to staticData.
  • Ch 47: Type Safety, uses the same declaration-merging technique (Register, StaticDataRouteOption) to enforce project-wide typing.