Documentation

useQuery

stable

Main React hook for reactive data fetching

The primary hook for reactive data fetching with automatic re-renders on state changes. Perfect for server state management with built-in caching, background updates, and error handling.

React Hook

Performance Tip

useQuery automatically deduplicates identical requests and shares cache between components.

Signature

function useQuery<TData, TError = Error>(
queryKey: QueryKey,
options?: QueryOptions<TData, TError>
): QueryState<TData, TError>

Parameters

queryKey

QueryKeyRequired

Unique identifier for the query. Can be a string, array, or object.

options

QueryOptions<TData, TError>

Optional configuration object. If no fetcher is provided, uses a previously registered fetcher.

options.fetcher

() => Promise<TData>

Function that returns a Promise resolving to the data. Optional if fetcher was already registered.

options.staleTime

numberDefault: 0

Time in milliseconds after which data is considered stale.

options.refetchOnSubscribe

'always' | 'stale' | falseDefault: 'stale'

When to refetch data when component subscribes.

Returns

Returns

QueryState<TData, TError>

Object containing the current query state

Properties:
dataTData | undefined

The fetched data, undefined while loading or on error

isLoadingboolean

True if the query is currently fetching for the first time

isFetchingboolean

True if the query is currently fetching (including background refetches)

errorTError | null

Error object if the query failed, null otherwise

isErrorboolean

True if the query failed with an error

isSuccessboolean

True if the query succeeded and has data

Examples

Basic Usage

Simple data fetching with useQuery

import { useQuery } from 'qortex-react';
function UserProfile({ userId }: { userId: string }) {
const { data, isLoading, error } = useQuery(
['user', userId],
{
fetcher: async () => {
const response = await fetch(`/api/users/${userId}`);
return response.json();
}
}
);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Hello, {data.name}!</div>;
}

With Configuration

Advanced configuration with stale time and refetch options

import { useQuery } from 'qortex-react';
function ProductList() {
const { data, isFetching } = useQuery(
'products',
{
fetcher: async () => {
const response = await fetch('/api/products');
return response.json();
},
staleTime: 5 * 60 * 1000, // 5 minutes
refetchOnSubscribe: 'stale'
}
);
return (
<div>
{isFetching && <div>Updating...</div>}
{data?.map(product => (
<div key={product.id}>{product.name}</div>
))}
</div>
);
}

Using Registered Fetcher

Using useQuery with a previously registered fetcher

import { useQuery, registerFetcher } from 'qortex-react';
// Register a fetcher once
registerFetcher('user-data', {
fetcher: async () => {
const response = await fetch('/api/user');
return response.json();
}
});
function UserProfile() {
// No need to provide fetcher - uses registered one
const { data, isLoading, error } = useQuery('user-data');
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Hello, {data.name}!</div>;
}

Behavior

Automatic Re-renders

Component automatically re-renders when query state changes

Background Updates

Stale data is refetched in the background without blocking UI

Error Handling

Built-in error states with retry capabilities

Caching

Automatic caching with configurable stale time

Best Practices

Do's

  • Use descriptive query keys that include all dependencies
  • Handle loading and error states appropriately
  • Set appropriate staleTime for your data freshness requirements
  • Use TypeScript for better type safety

Don'ts

  • Don't mutate the returned data object directly
  • Don't forget to handle error states in your UI
  • Don't use useQuery for one-time operations (use fetchQuery instead)
  • Don't create new objects in the fetcher function on every render