Skip to main content

Navigation

usePrefetchIntent

Calls the app's prefetch(key) when a person shows intent to open something: a mouse or pen resting on it, keyboard focus, or a touch beginning. Ouro owns the intent and the budget; the app owns what is fetched and where it is kept, so any data layer fits.

import { usePrefetchIntent } from "@/lib/ouro/use-prefetch-intent";

Example

const intent = usePrefetchIntent((id) => queryClient.prefetchQuery(recipe(id)), recipeId);
<a href={`/recipes/${recipeId}`} {...intent}>Pancakes</a>

Usage

The budget: a key is prefetched once until it goes stale, at most maxInflight prefetches run at once across the targets that share the function, a refused or skipped one is retried by the next intent, and nothing is prefetched when the browser asks to save data. The function's errors are swallowed, so a failed prefetch never breaks the page.

Spread it on a Link for a route: Link passes the handlers to its anchor.

Use instead when

  • Use the Speculation Rules API instead when the browser should prerender whole documents.

Parameters

prefetch
Type: ((key: string) => unknown) | undefined
key
Type: string
options
Type: PrefetchIntentOptions
{}

Returns

PrefetchIntentHandlers

Types

PrefetchIntentHandlers

The handlers usePrefetchIntent returns; spread them on the element.

interface PrefetchIntentHandlers {
  onPointerEnter: (event: PointerEvent<HTMLElement>) => void;
  onPointerLeave: (event: PointerEvent<HTMLElement>) => void;
  onFocus: (event: FocusEvent<HTMLElement>) => void;
  onTouchStart: (event: TouchEvent<HTMLElement>) => void;
}

PrefetchIntentOptions

Options for usePrefetchIntent.

interface PrefetchIntentOptions {
  /** How long a mouse or pen rests on the target before it counts as intent, in milliseconds. @default 65 */
  delay?: number | undefined;
  /** How many prefetches the app's function may have running at once, shared by the targets that use the same function. @default 2 */
  maxInflight?: number | undefined;
  /** How long a prefetched key stays fresh, in milliseconds; after that the next intent prefetches it again. @default 30000 */
  staleAfter?: number | undefined;
}