Skip to content

API reference > @kontsedal/olas-react > useQuery

useQuery() function ​

Subscribe a component to an AsyncState<T>: a query subscription or a local cache. Returns the plain values plus the action functions. See spec §20.10.

**Fine-grained.** The component re-renders only when a field it read during render changes. const { data } = useQuery(sub) does not re-render when a background refetch flips isFetching. A field read later, in an event handler or an effect, returns its current value and is tracked from then on. Spreading the result reads, and so tracks, every field.

Pass { suspense: true } to opt into React 18/19 Suspense semantics:

  • Until the first load settles the hook **throws** subscription.firstValue() — caught by the nearest <Suspense> boundary. - When that first load fails, the hook **throws** subscription.error — caught by the nearest <ErrorBoundary> (React itself doesn't ship one; use react-error-boundary or your own). A background-refetch failure that keeps the last-good data does NOT throw. - On success the hook returns synchronously and data is typed T. A load that settled on undefined (a select over an optional field, a fetcher that resolves nothing) returns it as it is. - A disabled (enabled: () => false) query suspends until it is enabled and loads, because firstValue() waits for the subscription to attach. That is what a dependent query wants. A query that is never enabled keeps the fallback up, and development builds warn once when that starts.

Refetches AFTER a first success do NOT re-suspend — only the initial load throws. reset() does NOT re-suspend either: it clears error/status but keeps data, so status returns to 'success' (spec §5). There is no built-in way to force re-suspension short of a fresh subscription.

Signature:

typescript
export declare function useQuery<T>(subscription: AsyncState<T>): UseQueryResult<T>;

Parameters ​

Parameter

Type

Description

subscription

AsyncState<T>

Returns:

UseQueryResult<T>

Example ​

tsx
function UserCard({ user }: { user: AsyncState<User> }) {
  const { data, error, isLoading } = useQuery(user)
  if (isLoading) return <p>Loading…</p>
  if (error) return <p role="alert">Could not load the user.</p>
  return <h1>{data?.name}</h1>
}

Released under the MIT License.