Capítulo 23 de 57

Chapter 23: Navigation

Core Idea

Every navigation in TanStack Router is relative between an origin (from) and destination (to) route, and this from/to pair, along with params/search/hash/state, is shared across every navigation API (Link, useNavigate, Navigate, router.navigate) so the same mental model and syntax applies everywhere.

Key Concepts

  • from / to: Core relative-navigation pair; if from is omitted, the router assumes navigation starts at root / and only autocompletes/type-checks absolute paths.
  • ToOptions: The base interface (from, to, params, search, hash, state, mask) shared by every navigation and route-matching API. params/search/hash/state each accept either a plain object or a function of the previous value.
  • NavigateOptions: Extends ToOptions with replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, reloadDocument, and href (a full built href for external targets).
  • LinkOptions: Extends NavigateOptions with target, activeOptions, preload (false | 'intent' | 'viewport' | 'render'), preloadDelay, and disabled.
  • <Link>: Renders a real <a> with a valid href; the standard, recommended way to navigate for anything user-clickable. Supports activeProps/inactiveProps, a data-status="active" attribute, activeOptions (exact, includeHash, includeSearch, explicitUndefined), and a function-as-children pattern exposing isActive.
  • useNavigate({ from }): Returns an imperative navigate function, intended for side-effect-driven navigation (e.g. after a successful async action), not for user-facing links/buttons.
  • <Navigate>: A component that performs an immediate client-side navigation on mount; not a substitute for a real server-side redirect.
  • router.navigate(): The most broadly available imperative navigation API, usable anywhere the router instance is accessible, including outside framework components.
  • useMatchRoute / <MatchRoute> / router.matchRoute: Check whether a route is currently matched or pending, useful for optimistic UI (e.g. showing a spinner while a link's destination is loading). useMatchRoute subscribes to router matching state (for rendering); router.matchRoute is a one-off, non-subscribing check for event handlers.
  • Special relative paths "." and "..": to="." reloads the current (or from) route (reruns loaders); to=".." navigates to the parent of the current/from route.
  • Optional parameter removal: With {-$param} optional segments, params: {} inherits current params, while explicitly setting a param to undefined removes it from the URL.

Code Examples

function Component() {
  const navigate = useNavigate({ from: '/posts/$postId' })

  const handleSubmit = async (e: FrameworkFormEvent) => {
    e.preventDefault()
    const response = await fetch('/posts', {
      method: 'POST',
      body: JSON.stringify({ title: 'My First Post' }),
    })
    const { id: postId } = await response.json()
    if (response.ok) {
      navigate({ to: '/posts/$postId', params: { postId } })
    }
  }
}
  • What it demonstrates: Imperative navigation after an async side effect, with from pre-bound in useNavigate to reduce boilerplate/errors.

Key Takeaways

  1. Prefer <Link> for anything the user clicks (it gets a real href, cmd/ctrl-click support, and active-state styling); reserve useNavigate/router.navigate for side-effect-driven navigation.
  2. None of the client-side navigation APIs replace a real server-side redirect for pre-render redirects, they all navigate after the app has already mounted.
  3. from matters for relative navigation and type-safety: without it, only absolute paths type-check and autocomplete; with it (especially via Route.useNavigate or route.fullPath), relative to values like . and .. resolve predictably.
  4. useMatchRoute (subscribing, for render-affecting checks) and router.matchRoute (non-subscribing, for one-off checks in event handlers) are optimized for different use cases, picking the wrong one causes either unnecessary re-renders or stale reads.

Connects To

  • Ch 24: Link Options, covers reusing ToOptions-shaped objects via linkOptions().
  • Ch 26: Path Params, detailed handling of the params field used throughout navigation.
  • Ch 27: Search Params, detailed handling of the search field.
  • Ch 29: Route Masking, expands on the mask option seen in ToOptions.
  • Ch 30: Navigation Blocking, relates to the ignoreBlocker option in NavigateOptions.