useRouteId
Returns the id of the page on screen, such as "cart" or "product.single", and renders the component again when the shopper navigates.
import { useRouteId } from '@salla.sa/twilight-theme-engine';In plain words
Every engine page has a short name: index for home, cart, product.single for a product. useRouteId() returns the name of the page on screen.
Compare it with the RouteId constants instead of typing the strings, and prefer the ready-made useIsHome()-style hooks when you only need one yes-or-no answer.
Signature
function useRouteId(): string // a RouteId value on engine pages, the router's own id on other routes, '' before any route resolves
Try it live
import type { ReactNode } from 'react';
import { RouteId, useRouteId } from '@salla.sa/twilight-theme-engine';
export function OnlyOn({ children }: { children: ReactNode }) {
const routeId = useRouteId();
return routeId === RouteId.INDEX ? <>{children}</> : null;
}
Example
import { useEffect } from 'react';
import { RouteId, useRouteId } from '@salla.sa/twilight-theme-engine';
import { track } from '../lib/analytics';
export function PageViewTracker() {
const routeId = useRouteId();
useEffect(() => {
if (!routeId) return;
track('page_view', { page_type: routeId === RouteId.PRODUCT_SINGLE ? 'product' : routeId });
}, [routeId]);
return null;
}
How it behaves
It is
useSyncExternalStoreover the request context. The TanStack router writes the id when the page hydrates and after every navigation resolves, mapping the router's route id to aRouteIdvalue withresolveRouteId(src/tanstack/router.tsx); subscribers render again.A route the id table does not know, such as a page your theme adds in
app/routes.ts, returns the raw router id, for example/{-$locale}/playground/$section/$slug/$entryon this page.Several addresses share an id:
/brands/$idand/$slug/brand-{$id}are bothbrands.single;/tags/$idand/$slug/tag-{$id}are bothproduct.index.tag.Also exported from
/providers.
Gotchas
On the server only the route class sync writes the id, and only while
routeClassistrue; withrouteClass={false}the hook returns''in the server render and the real id in the browser. See the page detection hooks for the fix.The engine's account pages (
/account/…) return raw router ids, notcustomer.*values, because the id table lists them without the/accountsegment.
Related
Seven yes-or-no hooks that tell a component which kind of store page is showing: home, product, cart, account, blog, brands or search.
RouteIdThe named list of every engine page id, so code compares with RouteId.CART instead of typing the string "cart".
useLocationReads the current address as the router sees it (path, parsed query, raw query, hash), in the server render and in the browser.