Docs

Query cache

For client-side data that isn't a route loader - lists, widgets, anything refetchable - Nifra ships a keyed query cache (TanStack-Query-style), agnostic across all five adapters.

useQuery / createQuery

useQuery(key, fn) (React, Preact, Vue and Svelte) and createQuery(key, fn) (Solid), each from the adapter's /query entry, subscribe a component to a cached, keyed query. Concurrent reads of the same key dedup into one in-flight fetch; results are cached with a staleTime (the third argument's option), a background refetch, and bounded GC. The query cache also has mutation and infinite-query bindings across the adapters, using each framework's reactive model.

Query keys are serialized structurally. Keep key arrays and objects stable when practical, and treat objects as immutable after the first query uses them: Nifra caches object hashes by identity, so mutating a reused object can leave it under its old hash, while creating a fresh equivalent key repeats serialization work. For example, derive one key from the current identity and reuse it for the render rather than mutating it after the query starts.

TS
import { useQuery, useQueryClient } from "@nifrajs/web-react/query"

function Profile({ id }: { id: string }) {
  // Keyed + cached. Concurrent useQuery's with the same key dedup into one fetch;
  // results are cached, with staleTime + background refetch.
  const { data, isPending, refetch } = useQuery(["user", id], () =>
    fetch(`/api/users/${id}`).then((r) => r.json()),
  )
  if (isPending) return <p>Loading…</p>
  return <h1>{data.name}</h1>
}

function CreateUser() {
  const qc = useQueryClient()
  // After a mutation, invalidate by key (or prefix) - matching queries refetch.
  return <button onClick={() => qc.invalidateQueries(["user"])}>Refresh</button>
}

Mutations and infinite queries

React and Preact expose useMutation and useInfiniteQuery. Vue exposes composables whose reactive state is read from refs. Svelte returns readable stores, and Solid exposes createMutation and createInfiniteQuery accessors. Each mutation has mutate, mutateAsync, reset, andcancel; each paged query exposes next/previous-page controls and page-availability state. Mutations remain client state bindings: the server action or endpoint still enforces authorization. Mutation functions receive a shared context with a signal as their second argument. onMutate receives that context second;onSuccess and onError receive it third; and onSettledreceives it fourth. Pass context.signal to fetch and check it before side effects after an await. cancel aborts that signal, rejects the local promise, and discards local results; the request or server action only stops if it honors the signal, and accepted server work may finish.

TS
// React / Preact: hooks with a promise-returning mutation.
// The mutation function receives a context with a shared AbortSignal as its second argument.
const saveProfile = async (profile, { signal }) => {
  const response = await fetch("/api/profile", {
    method: "PUT",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(profile),
    signal,
  })
  if (!response.ok) throw new Error("Profile save failed")
  return response
}
const save = useMutation(saveProfile)
await save.mutateAsync(profile)

// Vue: state is a ref; read it with .value.
const save = useMutation(saveProfile)
await save.mutateAsync(profile)
save.state.value.status

// Svelte: mutation and infinite-query bindings are readable stores.
const save = useMutation(saveProfile)
await save.mutateAsync(profile)
// In markup, read $save.status.

// Solid: state is exposed through accessors.
const save = createMutation(saveProfile)
await save.mutateAsync(profile)
save.state().status

SSR cache hydration

Query-cache hydration is separate from hydrating server-rendered markup. Create a fresh query client for each server request, prefetch the data, and pass its dehydrated state through Nifra route data. React and Preact use QueryClientProvider withHydrationBoundary; Solid accepts the state on QueryClientProvider; Vue and Svelte call provideQueryClient(client, state) in the app root before child queries initialize. The browser may keep one client for the app. Query state is cleared on identity changes, and in-flight mutation results are discarded at that boundary.

Every value included by dehydrate is serialized to the browser and is visible to that visitor, so dehydrate sends nothing by default. PassshouldDehydrateQuery to name the regular and infinite queries that are safe to send; pass () => true only when every successful query in that client is meant for the browser. Never include tokens or server-only fields.

TS
// Create one QueryClient for this server request.
const queryClient = createQueryClient({ now: () => Date.now() })
await queryClient.prefetchQuery(["profile", user.id], loadProfile)
const queryState = queryClient.dehydrate({
  // Nothing is sent unless this returns true: name what is safe for the visitor to read.
  shouldDehydrateQuery: ({ key }) => Array.isArray(key) && key[0] === "profile",
})

// Return queryState through the route's normal loader-data serializer.
// On the client, seed the app's client before query components mount.

Invalidation

After a mutation, useQueryClient().invalidateQueries(key) marks matching entries stale (by exact key or array prefix) and refetches the mounted ones - no manual cache surgery.

In an app with live refresh, a query can name the live keys its data depends on: useQuery(key, fn, { live: [`post:${id}`] }) refetches whenever the server publishes one of them.

Sign-in and sign-out

A cached query never answers for the next visitor. identityChanged() from @nifrajs/web/client clears every query client in the page: mounted queries go back to pending and refetch, the rest drop their data. A fetch still loading loads once more for the new visitor before it settles. In an app with a keepAlive route, the identity epoch cookie a sign-in or sign-out response rotates does the same on the client's next read.

It's the same agnostic core under every adapter: the cache, dedup, and invalidation logic live in @nifrajs/web; each binding is a thin wrapper in its framework's own reactivity (useSyncExternalStore, a signal, a shallowRef, a store).