Prefetching
If a lesson page needs a large module, loading it while a reader considers a link can reduce the wait after selection. Prefetch is optional warming: a route callback prepares resources, while the page still owns reading its data or module through the appropriate cache.
Do not put mandatory access checks in prefetch. It does not run on initial rendering, and speculative calls skip guards entirely. Use route guards for mandatory checks, and authorize every preload request at the backend. Speculation must not mutate server state.
Warm a route module
Section titled “Warm a route module”Create the default-exported src/LessonPage.tsx from Defining Routes. In your route-table module, reuse the same import function for React lazy loading and prefetch:
import { lazy } from 'react'import { createRouter } from '@studiolambda/router/react'
function loadLessonPage() { return import('./LessonPage')}
const LessonPage = lazy(loadLessonPage)export const matcher = createRouter((route) => { route('/lessons/:slug') .prefetch(async () => { try { await loadLessonPage() } catch (error) { console.error('lesson preload failed', error) } }) .render(LessonPage)})The module system caches imports; Router does not invent a module cache. Catching the warming failure lets navigation continue to the page’s own render/error boundary rather than failing at the optional preload phase. A later lazy import can still fail, so keep that boundary.
For data preloading, call your data layer’s preload API from the callback and let the page read the same key. The callback’s return type is void | Promise<void>: it does not produce a loader-data prop. Initial visits must work without this warming step.
Choose when to speculate
Section titled “Choose when to speculate”Inside your routed page or layout, opt a link into hover warming:
import { Link } from '@studiolambda/router/react'
export default function SuggestedLesson() { return ( <Link href="/lessons/routing" prefetch="hover"> Read the routing lesson </Link> )}Without prefetch, Link sets up no speculative work. 'hover' listens for mouseenter; 'viewport' uses IntersectionObserver. Hover is a narrow intent signal; viewport can start more work and requires observer support in the browser.
once defaults to true. The hover listener is one-shot. The viewport observer disconnects after its first callback, even if no entry intersects. Use once={false} if the observer must remain available after an initial nonintersecting callback. This only changes the DOM subscription; the matcher attempt cache still deduplicates actual prefetch calls.
Link and usePrefetchEffect ignore callback results and do not catch errors/rejections. Handle expected speculative failures inside the route callback, as the module example does. Otherwise a preload failure can become an unhandled error even though no navigation occurred.
Start warming manually
Section titled “Start warming manually”For an application-owned trigger, usePrefetch returns the callback result to the initiating component:
import { usePrefetch } from '@studiolambda/router/react'
export default function WarmLessonButton() { const prefetch = usePrefetch()
function onClick() { try { Promise.resolve(prefetch('/lessons/routing')).catch(console.error) } catch (error) { console.error(error) } }
return <button onClick={onClick}>Prepare routing lesson</button>}It returns undefined for an unmatched path, a route without prefetch, or a duplicate attempt. A synchronous callback error throws immediately; an asynchronous error rejects the returned promise. An explicit { matcher } option selects a table instead of context.
For a custom DOM component, import useRef from React and usePrefetchEffect from the router:
function LessonCard() { const ref = useRef<HTMLDivElement>(null) usePrefetchEffect(ref, { href: '/lessons/routing', on: 'viewport', once: false }) return <div ref={ref}>Routing lesson preview</div>}The hook cleans up its listener/observer on unmount, not work already started. Undefined on attaches nothing. Undefined href suppresses trigger work but can still attach a subscription. Both fields are required keys in PrefetchEffectOptions, even when their values are undefined.
Distinguish attempts from cached data
Section titled “Distinguish attempts from cached data”Speculative calls share an attempt cache keyed by matcher identity and parsed pathname. It records that the callback was attempted, not that data is ready:
/lessons/routing?view=notesand/lessons/routing?view=full#summaryshare one key.- The attempt is recorded before invoking the callback and remains after failure.
- A duplicate caller receives
undefined, not the first caller’s in-flight promise. - Routers sharing one matcher share attempts; separate matchers do not.
- Real navigation always runs its prefetch callbacks again and does not use this cache.
If your preload depends on search parameters, do not assume speculative query variants all run. Use your data layer’s own keying policy and make the page’s normal read authoritative.
After your application invalidates data or changes users, clear bookkeeping for the exact matcher:
import { clearPrefetchCache } from '@studiolambda/router/react'
clearPrefetchCache(matcher)This allows a later speculative attempt. It does not erase application data, cancel work, clear the module cache, or rearm one-shot DOM triggers. Clear private data in its actual owner too; clearing only this set is not a logout security boundary.
Understand navigation-time prefetch
Section titled “Understand navigation-time prefetch”During a real intercepted navigation or custom action, Router awaits guards and then prefetch before proceeding. Multiple callbacks run sequentially, parent-first. A thrown/rejected callback fails navigation unless your callback handles the failure. “Optional warming” describes its role, not an automatic ignore-errors policy.
Cancelable events run these callbacks before URL commit. Noncancelable interceptable events run them afterward; failure can leave the address bar ahead of the rendered page. Guards/prefetch do not receive a cancellation signal and arbitrary work is not automatically aborted.
PrefetchContext contains { params, url, controller }. The controller is native during valid precommit, a no-op stub during speculation, and rejects precommit-only operations after commit. A speculative redirect() does not navigate or preload the target, though it still stops later callbacks in the builder’s source prefetch chain. Use redirect routes for URL migration, not prefetch as an authentication protocol.