# Server Data (crow-query) (https://crow.build/docs/stack/query)

`crow-query` is Crow's platform-free server-state manager. Stateless `query` and `infiniteQuery` descriptors define how to fetch data; a context-provided `QueryClient` manages caching, request deduplication, refcounting, per-entry epochs, prefetching, and foreground revalidation.

## Declaring Queries [#declaring-queries]

Define descriptors once at the top level — zero coupling to any screen or ViewModel:

```kotlin
val PokemonPages = infiniteQuery(
    initialCursor = { _: Unit -> 0 },
    nextCursor = { page, pages -> if (page.size < 20) null else pages.size },
    policy = QueryPolicy(staleTime = 5.minutes),
) { _, page ->
    PokeApi.fetchPage(page)
}

val PokemonDetails = query(
    policy = QueryPolicy(staleTime = 10.minutes),
) { name: String ->
    PokeApi.fetchDetails(name)
}
```

## Observing & Prefetching in UI [#observing--prefetching-in-ui]

Provide a `QueryClient` at your app root with `LocalQueryClient(client) { ... }`, then observe queries directly inside `@Ui` functions:

```kotlin
@Ui
fun PokemonDetailsScreen(name: String) {
    val details = PokemonDetails { name }

    Errored(fallback = { err, retry ->
        ErrorView(err.message, onRetry = { details.reload(); retry() })
    }) {
        Loading(fallback = { DetailsSkeleton() }) {
            DetailsContent(details.value, refreshing = details.isFetching)
        }
    }
}
```

Prefetch on tap (or hover/scroll) so the detail screen opens instantly from cache:

```kotlin
val client = LocalQueryClient.current
PokemonCard(
    pokemon = item,
    onClick = {
        PokemonDetails.prefetch(item.name, client)
        router.navigate(Routes.Details(item.name))
    },
)
```

## Why `crow-query` Beats Bolted-On Caches [#why-crow-query-beats-bolted-on-caches]

- **Non-holding background revalidation**: Stale cached data displays immediately and refreshes silently in the background **without holding** a UI transition. Cold cache misses wait cleanly under `Loading`.
- **Epoch-protected mutations**: Running a mutation inside `action { ... }` with `PokemonDetails.optimistic(name, client) { ... }` and `PokemonDetails.invalidate(name, client).await()` increments the entry epoch, cancelling stale in-flight fetches so an older network response can never overwrite a newer mutation (verified by a 500-seed interleaving fuzzer).
- **Lifecycle wiring**: Hook `client.onForeground()` and `client.trim()` into your host (`ProcessHost.isForeground` / `onTrimMemory`) to automatically refresh stale active queries and release unused cache entries under memory pressure.