Navigation
Most navigation should start with an anchor: users can open it in another tab, copy its address, and use browser history. Use programmatic navigation when an application event chooses the destination instead, such as a completed workflow.
These examples run inside a page or layout middleware in a mounted Router. The browser must support the Navigation API; the library does not replace it with a History API implementation.
Support must include the interception features your routes use. In particular, guarded/prefetched cancelable navigation relies on native precommit handling, and redirect routes rely on the precommit controller’s redirect capability. A window.navigation presence check is an initial compatibility check, not proof of every feature; verify those flows in each browser you support.
Navigate from a link
Section titled “Navigate from a link”Use Link for an ordinary destination:
import { Link } from '@studiolambda/router/react'
export default function NextLesson() { return <Link href="/lessons/navigation">Next lesson</Link>}Link renders an anchor, not a button that impersonates one. Router listens to native navigate events, so plain <a href="/lessons/navigation"> works too. Link adds active styling and optional prefetch.
Router leaves events alone when canIntercept is false, the navigation is hash-only, or a download is requested. External/document navigations remain subject to browser rules. Do not assume that every link click reaches a React state update.
Navigate from an application event
Section titled “Navigate from an application event”For a button whose action chooses a route, call useNavigate. The hook delegates to the supplied navigation object’s navigate method:
import { useNavigate } from '@studiolambda/router/react'
export default function OpenNotebook() { const navigate = useNavigate()
function onClick() { try { const result = navigate('/lessons', { history: 'replace' }) Promise.all([result.committed, result.finished]).catch((error) => { console.error('could not open lessons', error) }) } catch (error) { console.error('could not start navigation', error) } }
return <button onClick={onClick}>Open notebook</button>}Use 'replace' when the old entry should not remain in Back history; use 'push' for a new entry. Omitting options preserves native Navigation API defaults. The router does not sanitize destinations; do not feed unvalidated user-controlled URLs into navigation or redirect APIs.
The return value is a native NavigationResult, not Promise<void>. committed concerns the history-entry commit; finished concerns native navigation completion. Observe both promises when you initiate navigation, since either can reject. A synchronous invalid-call error must be caught separately. Completion does not prove that a data source succeeded or that every Suspense subtree has painted.
Offer back and forward controls
Section titled “Offer back and forward controls”If navigation controls are part of your UI, disable them when the history direction is unavailable. useBack and useForward keep their availability values reactive through currententrychange:
import { useBack } from '@studiolambda/router/react'
export default function BackButton() { const { back, canGoBack } = useBack()
function onClick() { try { const result = back() Promise.all([result.committed, result.finished]).catch(console.error) } catch (error) { console.error(error) } }
return <button disabled={!canGoBack} onClick={onClick}>Back</button>}useForward() returns { forward, canGoForward } with the same options/result contract. Native impossible traversals can reject; the availability flag is a useful UI hint, not a substitute for handling results.
Understand when the URL and UI change
Section titled “Understand when the URL and UI change”A commit is the browser accepting the destination history entry. A precommit check runs before that point; a postcommit handler runs afterward. For eligible cancelable events, Router runs:
- Match the destination pathname.
- Await its mandatory guards, parent first.
- Await its prefetch callbacks, parent first; rematch and recheck any successful redirect target.
- Let the URL commit.
- Update the rendered match in a React transition, or run an opted-in form action.
An event can be interceptable without being cancelable. For noncancelable interceptable events, notably history traversal, Router runs guards and prefetch after the URL commits, but before changing React content or dispatching the action. If a check rejects, the old rendered route remains while the address bar can already show the new URL. usePathname() and useSearchParams() describe rendered state, not an unconditional mirror of currentEntry.
Postcommit prefetch gets a restricted controller: redirect() and addHandler() throw InvalidStateError. Redirects also require a native push/replace navigation, not traverse or reload. Router does not synthesize a second navigation to hide those restrictions. See redirects and failures when choosing recovery behavior.
POST forms have a separate ownership decision before any checks. Without an explicit destination formHandler, Router does not intercept them at all. Form ownership explains why this preserves the server submission rather than silently dropping its body.
Observe completion and failure
Section titled “Observe completion and failure”For application-wide reporting, pass onNavigateSuccess and onNavigateError to Router. They observe the native navigatesuccess and navigateerror events, not initial page rendering or an application-defined “all data ready” milestone.
For a separate observer inside your layout, use the explicit navigation object:
import { useNavigation, useNavigationEvents } from '@studiolambda/router/react'
export default function NavigationReporter() { const navigation = useNavigation() useNavigationEvents(navigation, { onNavigateSuccess() { console.info('native navigation completed') }, onNavigateError(error) { console.error('native navigation failed', error) }, }) return null}The hook also accepts onNavigate(event). It owns subscription cleanup on unmount and uses current callbacks without requiring you to memoize them. Use one reporting owner to avoid logging the same failure through Router and an observer unintentionally. Reporting a native event does not consume the result promises returned to a caller.
Scope cancellation correctly
Section titled “Scope cancellation correctly”useNavigationSignal() returns null initially, then the native NavigateEvent.signal associated with the rendered route. It is an event-cancellation signal, not a route-unmount signal. A completed navigation’s signal need not abort when you later leave that page.
Use your data layer’s cancellation policy or an application-owned AbortController for work that must stop on unmount. Guards and prefetch callbacks receive params and URL, but no event signal. Form handlers do receive the native event and can pass event.signal to their own requests. Router does not cancel arbitrary promises or undo mutations when navigation fails.
Use search parameters for shareable filters, and the hook reference when you need the exact return contracts.