Skip to content

Hooks Reference

Use hooks when a page or layout needs location, navigation, or route-lifecycle state. Import every hook below from @studiolambda/router/react and call it inside a React component or custom hook. Router normally supplies their contexts; it does not accept children, so put shared controls in middleware.

The short calls below are reference fragments, not standalone components. Task guides provide the surrounding UI, setup, and failure handling.

NeedHooks
Read the rendered locationuseParams, usePathname, useSearchParams
Start navigationuseNavigate, useBack, useForward
Inspect lifecycleuseNavigationType, useNavigationSignal, useIsPending
Build a link or preload triggeruseActiveLinkProps, usePrefetch, usePrefetchEffect
Integrate native navigationuseNavigation, useNavigationEvents
Build advanced adaptersuseNextMatch, useNavigationHandlers

useParams() returns Record<string, string> containing the matched dynamic and wildcard captures, or {} for a static route. It throws without ParamsContext.

const { slug } = useParams()

Captures remain URL-encoded and are not schema-validated. The record is shared; treat it as read-only. There is no route-specific generic or automatic numeric conversion. See parameter validation.

usePathname() returns the rendered match’s pathname as a string, excluding search and hash. It throws without PathnameContext.

const pathname = usePathname()

After a failed noncancelable postcommit check it can lag the browser address bar. It describes rendered state, not every native history-entry change.

useSearchParams() returns [URLSearchParams, setSearchParams]. It reads rendered UrlContext state and requires navigation context for the setter. Null URL context produces empty params; malformed context URLs throw.

const [params, setSearchParams] = useSearchParams()
const topic = params.get('topic') ?? 'all'

SearchParamsUpdater accepts a URLSearchParams, a Record<string, string>, or a function receiving fresh mutable params and returning either form. Each setter call replaces the complete query, preserves the hash, and returns NavigationResult. SetSearchParamsOptions.history defaults to 'replace'. Mutating the getter alone does not navigate. See updating filters safely.

useNavigate() returns (url: string, options?: NavigationNavigateOptions) => NavigationResult. It delegates to the supplied navigation object and requires NavigationContext.

const navigate = useNavigate()

Call it with a validated application destination. Catch synchronous errors and observe both committed and finished promises; programmatic navigation shows the full event handler. The memory adapter returns resolved results without moving.

useBack() returns UseBackResult: { back, canGoBack }. back(options?: NavigationOptions) returns native NavigationResult. The availability boolean updates on currententrychange; the hook requires NavigationContext and removes its listener on cleanup.

const { back, canGoBack } = useBack()

Disable unavailable controls and still handle native failure promises. The Back button example includes both. Memory navigation always reports unavailable but returns an unchanged resolved result if called.

useForward() returns UseForwardResult: { forward, canGoForward }, mirroring useBack for forward history. forward(options?: NavigationOptions) returns NavigationResult.

const { forward, canGoForward } = useForward()

Availability is reactive through currententrychange. It requires navigation context and has the same native-error and fixed-memory limitations as Back.

useNavigationType() returns 'push' | 'replace' | 'reload' | 'traverse' | null. It is null initially and throws when NavigationTypeContext is absent.

const type = useNavigationType()

The value belongs to the rendered match. Failed checks and unchanged custom actions do not replace it. It is not an event counter or an initial page-view notification.

useNavigationSignal() returns AbortSignal | null. It is null initially and throws when NavigationSignalContext is absent.

const signal = useNavigationSignal()

The signal belongs to the native event that produced the rendered match, not the route component’s lifetime. A completed event need not abort when a later navigation starts. Own a separate cancellation policy for unmount-sensitive work; see cancellation scope.

useIsPending() returns the boolean from Router’s React transition tuple. It requires TransitionContext.

const isPending = useIsPending()

It does not cover initial guard suspension or all precommit work. To read the same state above Router, pass an explicit transition tuple.

useActiveLinkProps(href, options?) returns { isActive, props }. href accepts string | undefined; ActiveLinkOptions.exact defaults to true. props contains data-active: true and aria-current: 'page' when active, otherwise undefined values.

const { isActive, props } = useActiveLinkProps('/lessons', { exact: false })

Spread props onto your anchor and use isActive for styling. Without pathname context it returns inactive rather than throwing. Prefix mode requires equality or the href pathname followed by /; /lessons-old is not a child of /lessons, and / is not a catch-all.

Query, hash, and origin do not participate. Relative hrefs use http://localhost/ as their base; invalid URLs throw when extraction occurs. This is not a same-origin check. For a complete ready-made anchor, use Link.

usePrefetch(options?) returns (url: string) => void | Promise<void>. PrefetchOptions.matcher overrides MatcherContext, which otherwise defaults to an empty table.

const prefetch = usePrefetch({ matcher })

The returned function invokes the matched route’s prefetch without guards, using a no-op controller. Unmatched, callback-free, and already-attempted paths return undefined. Synchronous errors throw; async errors reject. Speculative attempts deduplicate by pathname per matcher, including failures and query/hash variants. Duplicate callers do not share a pending promise. Real navigation ignores this cache.

clearPrefetchCache(matcher) clears only attempt bookkeeping for that exact matcher. It does not invalidate data or cancel work. See prefetching for safe requests, error handling, and invalidation.

usePrefetchEffect(ref, options) attaches a DOM trigger and returns nothing. ref is a React RefObject<Element | null>. PrefetchEffectOptions requires href: string | undefined and on: PrefetchStrategy | undefined, with optional once and matcher.

usePrefetchEffect(ref, { href: '/lessons/routing', on: 'hover' })

PrefetchStrategy is 'hover' | 'viewport'. once defaults to true; viewport disconnects after its first observer callback even when nothing intersects. False keeps the subscription active but does not bypass matcher deduplication. Undefined on attaches nothing; undefined href suppresses calls, not necessarily subscriptions.

Cleanup removes listeners/observers, not started work. Viewport mode requires IntersectionObserver. The hook ignores results and does not catch errors: handle expected preload failures inside the route callback, as with Link.

useNavigation() returns the supplied Navigation object and throws without NavigationContext. It does not directly fall back to window.navigation; Router establishes that default and provides it to descendants.

const navigation = useNavigation()

Prefer narrower hooks for ordinary UI. Raw native entries/state methods are available only if the supplied implementation actually supports them. The memory adapter implements a deliberately smaller subset.

useNavigationEvents(navigation, handlers) subscribes to an explicit object and returns nothing. No Router provider is required if you already have that object. NavigationEventHandlers has three optional callbacks:

  • onNavigate(event: NavigateEvent) receives the event.
  • onNavigateSuccess() receives no arguments.
  • onNavigateError(error: unknown) receives the error extracted from the native error event.
useNavigationEvents(navigation, { onNavigateError: console.error })

It owns cleanup on unmount/object replacement and reads current callbacks through React effect events. These native lifecycle events do not report initial render failures. See the reporter component for setup.

useNextMatch(options?) returns (destination: string | null, notFound: ComponentType) => Resolved<Handler>. NextMatchOptions.matcher overrides the context matcher.

const resolve = useNextMatch({ matcher })
const match = resolve('/lessons/routing', MissingPage)

Use this to inspect a match, not to bypass Router. It runs no guards, prefetch, redirects, or middleware. Unmatched, null, and empty destinations return a synthetic handler for notFound with empty params. Null/empty input does not try to match /. Relative strings resolve against http://localhost/; malformed URLs throw.

useNavigationHandlers(transition?) returns createPrecommitHandler and createHandler factories. Pass a useTransition() tuple explicitly or provide TransitionContext; without either it throws.

const { createPrecommitHandler, createHandler } = useNavigationHandlers()

createPrecommitHandler(options) accepts PrecommitHandlerOptions: required params/url and optional guard/prefetch. It returns undefined if neither callback exists; otherwise it returns an async controller callback that awaits guard before prefetch. Rejection propagates. It retains the supplied objects rather than cloning them.

createHandler(callback) accepts a React TransitionFunction and returns a no-argument callback producing Promise<void>. It runs the callback in startTransition, resolves when that callback completes, and rejects if it throws/rejects. Resolution does not guarantee every suspended subtree has painted.

These are low-level primitives, not a custom-router kit with all Router semantics included. They do not implement initial guards, redirect rematching/loop limits, POST ownership, or the noncancelable postcommit policy. Use Router unless you deliberately own those responsibilities and test them against the browser.

Explicit providers are useful for isolated controls/tests, but providing a context does not execute checks or install routing. Router supplies all eight values to its rendered subtree:

ContextValueDefault without provider
MatcherContextMatcher<Handler>Empty matcher
NavigationContextNavigation or nullNull
ParamsContextString record or nullNull
PathnameContextString or nullNull
UrlContextFull URL string or nullNull
TransitionContextuseTransition() tuple or nullNull
NavigationTypeContextNative type or nullUndefined sentinel
NavigationSignalContextAbortSignal or nullUndefined sentinel

Null for initial signal/type is a valid provided value; undefined means no provider and makes their hooks throw. The components page covers RouterProps, LinkProps, LinkRenderProps, and MiddlewaresProps. Defining Routes covers RouteBuilder, RouteFactory, and Handler; the related task guides explain GuardContext/GuardFunc, PrefetchContext/PrefetchFunc, RedirectTarget, FormHandler, and MiddlewareProps.

MemoryNavigationOptions belongs to server rendering. Core-only Matcher<T>, Resolved<T>, Options<T>, and Node<T> come from @studiolambda/router, not the React entry point. extractPathname is the React-entry helper described in pattern matching.