useQuery
const {data,error,failureCount,isError,isFetchedAfterMount,isFetching,isIdle,isLoading,isPreviousData,isStale,isSuccess,refetch,remove,status,} = useQuery(queryKey, queryFn?, {cacheTime,enabled,initialData,isDataEqual,keepPreviousData,notifyOnStatusChange,onError,onSettled,onSuccess,queryFnParamsFilter,queryKeySerializerFn,refetchInterval,refetchIntervalInBackground,refetchOnMount,refetchOnReconnect,refetchOnWindowFocus,retry,retryDelay,staleTime,structuralSharing,suspense,useErrorBoundary,})// or using the object syntaxconst queryInfo = useQuery({queryKey,queryFn,enabled,})
Options
queryKey: string | unknown[]
enabled
is not set to false
).queryFn: (...params: unknown[]) => Promise<TData>
enabled: boolean | unknown
false
to disable this query from automatically running.retry: boolean | number | (failureCount: number, error: TError) => boolean
false
, failed queries will not retry by default.true
, failed queries will retry infinitely.number
, e.g. 3
, failed queries will retry until the failed query count meets that number.retryDelay: (retryAttempt: number) => number
retryAttempt
integer and returns the delay to apply before the next attempt in milliseconds.attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
applies exponential backoff.attempt => attempt * 1000
applies linear backoff.staleTime: number | Infinity
Infinity
, query will never go stalecacheTime: number | Infinity
Infinity
, will disable garbage collectionrefetchInterval: false | number
refetchIntervalInBackground: boolean
true
, queries that are set to continuously refetch with a refetchInterval
will continue to refetch while their tab/window is in the backgroundrefetchOnMount: boolean | "always"
true
true
, the query will refetch on mount if the data is stale.false
, the query will not refetch on mount."always"
, the query will always refetch on mount.refetchOnWindowFocus: boolean | "always"
true
true
, the query will refetch on window focus if the data is stale.false
, the query will not refetch on window focus."always"
, the query will always refetch on window focus.refetchOnReconnect: boolean | "always"
true
true
, the query will refetch on reconnect if the data is stale.false
, the query will not refetch on reconnect."always"
, the query will always refetch on reconnect.notifyOnStatusChange: boolean
false
to only re-render when there are changes to data
or error
.true
.onSuccess: (data: TData) => void
onError: (error: TError) => void
onSettled: (data?: TData, error?: TError) => void
select: (data: TData) => unknown
suspense: boolean
true
to enable suspense mode.true
, useQuery
will suspend when status === 'loading'
true
, useQuery
will throw runtime errors when status === 'error'
initialData: unnown | () => unknown
staleTime
has been set.keepPreviousData: boolean
false
data
will be kept when fetching new data because the query key changed.queryFnParamsFilter: (...params: unknown[]) => unknown[]
queryFn
.queryFnParamsFilter: params => params.slice(1)
.structuralSharing: boolean
true
false
, structural sharing between query results will be disabled.Returns
status: String
idle
if the query is idle. This only happens if a query is initialized with enabled: false
and no initial data is available.loading
if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg isFetching === true
error
if the query attempt resulted in an error. The corresponding error
property has the error received from the attempted fetchsuccess
if the query has received a response with no errors and is ready to display its data. The corresponding data
property on the query is the data received from the successful fetch or if the query is in manual
mode and has not been fetched yet data
is the first initialData
supplied to the query on initialization.isIdle: boolean
status
variable above, provided for convenience.isLoading: boolean
status
variable above, provided for convenience.isSuccess: boolean
status
variable above, provided for convenience.isError: boolean
status
variable above, provided for convenience.data: TData
undefined
.error: null | TError
null
isStale: boolean
true
if the data in the cache is invalidated or if the data is older than the given staleTime
.isPreviousData: boolean
true
when keepPreviousData
is set and data from the previous query is returned.isFetchedAfterMount: boolean
true
if the query has been fetched after the component mounted.isFetching: boolean
true
so long as manual
is set to false
true
if the query is currently fetching, including background fetching.failureCount: number
0
when the query succeeds.refetch: (options: { throwOnError: boolean }) => Promise<TData | undefined>
throwOnError: true
optionremove: () => void
useQueries
The useQueries
hook can be used to fetch a variable number of queries:
const results = useQueries([{ queryKey: ['post', 1], queryFn: fetchPost },{ queryKey: ['post', 2], queryFn: fetchPost },])
Options
The useQueries
hook accepts an array with query option objects identical to the useQuery
hook.
Returns
The useQueries
hook returns an array with all the query results.
useInfiniteQuery
const queryFn = (...queryKey, fetchMoreVariable) // => Promiseconst {isFetchingMore,fetchMore,canFetchMore,...queryInfo} = useInfiniteQuery(queryKey, queryFn, {...queryOptions,getFetchMore: (lastPage, allPages) => fetchMoreVariable})
Options
The options for useInfiniteQuery
are identical to the useQuery
hook with the addition of the following:
getFetchMore: (lastPage, allPages) => fetchMoreVariable | boolean
Returns
The returned properties for useInfiniteQuery
are identical to the useQuery
hook, with the addition of the following:
isFetchingMore: false | 'next' | 'previous'
paginated
mode, this will be true
when fetching more results using the fetchMore
function.fetchMore: (fetchMoreVariableOverride) => Promise<TData | undefined>
fetchMoreVariableOverride
allows you to optionally override the fetch more variable returned from your getFetchMore
option to your query function to retrieve the next page of results.canFetchMore: boolean
paginated
mode, this will be true
if there is more data to be fetched (known via the required getFetchMore
option function).useMutation
const [mutate,{ status, isIdle, isLoading, isSuccess, isError, data, error, reset },] = useMutation(mutationFn, {onMutate,onSuccess,onError,onSettled,throwOnError,useErrorBoundary,})const promise = mutate(variables, {onSuccess,onSettled,onError,throwOnError,})
Options
mutationFn: (variables) => Promise
variables
is an object that mutate
will pass to your mutationFn
onMutate: (variables) => Promise | snapshotValue
onError
and onSettled
functions in the event of a mutation failure and can be useful for rolling back optimistic updates.onSuccess: (data, variables) => Promise | undefined
mutate
-level onSuccess
handler (if it is defined)onError: (err, variables, onMutateValue) => Promise | undefined
mutate
-level onError
handler (if it is defined)onSettled: (data, error, variables, onMutateValue) => Promise | undefined
mutate
-level onSettled
handler (if it is defined)throwOnError
false
true
if failed mutations should re-throw errors from the mutation function to the mutate
function.useErrorBoundary
useErrorBoundary
value, which is false
Returns
mutate: (variables, { onSuccess, onSettled, onError, throwOnError }) => Promise
variables: any
mutationFn
.useMutation
hook.useMutation
-level options.status: String
idle
initial status prior to the mutation function executing.loading
if the mutation is currently executing.error
if the last mutation attempt resulted in an error.success
if the last mutation attempt was successful.isIdle
, isLoading
, isSuccess
, isError
: boolean variables derived from status
data: undefined | unknown
undefined
error: null | TError
reset: () => void
QueryClient
The QueryClient
can be used to interact with a cache:
import { QueryClient, QueryCache } from 'react-query'const cache = new QueryCache()const client = new QueryClient({cache,defaultOptions: {queries: {staleTime: Infinity,},},})await client.prefetchQuery('posts', fetchPosts)
Its available methods are:
fetchQueryData
prefetchQuery
getQueryData
setQueryData
refetchQueries
invalidateQueries
cancelQueries
removeQueries
watchQuery
watchQueries
isFetching
setQueryDefaults
Options
cache: QueryCache
defaultOptions: DefaultOptions
client.fetchQueryData
fetchQueryData
is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with the error. Specify a staleTime
to only trigger a fetch when the data is stale. Use the prefetchQuery
method if you just want to fetch a query without needing the result.
If the query exists and the data is not invalidated and also not older than the given staleTime
, then the data from the cache will be returned. Otherwise it will try to fetch the latest data.
The difference between using
fetchQueryData
andsetQueryData
is thatfetchQueryData
is async and will ensure that duplicate requests for this query are not created withuseQuery
instances for the same query are rendered while the data is fetching.
try {const data = await client.fetchQueryData(queryKey, queryFn)} catch (error) {console.log(error)}
Set a stale time to only fetch when the data is older than the specified time:
try {const data = await client.fetchQueryData(queryKey, queryFn, {staleTime: 10000,})} catch (error) {console.log(error)}
Options
The options for fetchQueryData
are exactly the same as those of useQuery
.
Returns
Promise<TData>
client.prefetchQuery
prefetchQuery
is an asynchronous method that can be used to prefetch a query before it is needed or rendered with useQuery
and friends. The method works the same as fetchQueryData
except that is will not throw or return any data.
await client.prefetchQuery(queryKey, queryFn)
You can even use it with a default queryFn in your config!
await client.prefetchQuery(queryKey)
Options
The options for prefetchQuery
are exactly the same as those of useQuery
.
Returns
Promise<void>
client.getQueryData
getQueryData
is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, undefined
will be returned.
const data = client.getQueryData(queryKey)
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersReturns
data: TData | undefined
undefined
if the query does not exist.client.setQueryData
setQueryData
is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created. If the query is not utilized by a query hook in the default cacheTime
of 5 minutes, the query will be garbage collected.
The difference between using
setQueryData
andfetchQueryData
is thatsetQueryData
is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or usefetchQueryData
to handle the asynchronous fetch.
client.setQueryData(queryKey, updater)
Options
queryKey: QueryKey
Query Keysupdater: unknown | (oldData: TData | undefined) => TData
Using an updater value
setQueryData(queryKey, newData)
Using an updater function
For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
setQueryData(queryKey, oldData => newData)
client.refetchQueries
The refetchQueries
method can be used to refetch queries based on certain conditions.
Examples:
// refetch all active queries:await client.refetchQueries()// refetch all active stale queries:await client.refetchQueries({ stale: true })// refetch all queries:await client.refetchQueries({ active: true, inactive: true })// refetch all active queries partially matching a query key:await client.refetchQueries(['posts'])// refetch all active queries exactly matching a query key:await client.refetchQueries(['posts', 1], { exact: true })
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersrefetchOptions?: RefetchOptions
:throwOnError?: boolean
true
, this method will throw if any of the query refetch tasks fail.Returns
This function returns a promise that will resolve when all of the queries are done being refetched. By default, it will not throw an error if any of those queries refetches fail, but this can be configured by setting the throwOnError
option to true
client.invalidateQueries
The invalidateQueries
method can be used to invalidate single or multiple queries in the cache based on their query keys or other filters. Queries marked as invalid will be refetched on window focus, a reconnect or when components mount.
client.invalidateQueries('posts')
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query Filtersclient.cancelQueries
The cancelQueries
method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.
await client.cancelQueries('posts', { exact: true })
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersReturns
This method does not return anything
client.removeQueries
The removeQueries
method can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query.
client.removeQueries(queryKey, { exact: true })
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersReturns
This method does not return anything
client.watchQuery
The watchQuery
method returns a QueryObserver
instance which can be used to watch a query.
const observer = client.watchQuery('posts')observer.subscribe(result => {console.log(result)observer.unsubscribe()})
Options
The options for watchQuery
are exactly the same as those of useQuery
.
Returns
QueryObserver
client.watchQueries
The watchQueries
method returns a QueriesObserver
instance to watch multiple queries.
const observer = client.watchQueries([{ queryKey: ['post', 1], queryFn: fetchPost },{ queryKey: ['post', 2], queryFn: fetchPost },])observer.subscribe(result => {console.log(result)observer.unsubscribe()})
Options
The options for watchQueries
are exactly the same as those of useQueries
.
Returns
QueriesObserver
client.isFetching
This isFetching
method returns an integer
representing how many queries, if any, in the cache are currently fetching (including background-fetching, loading new pages, or loading more infinite query results)
if (client.isFetching()) {console.log('At least one query is fetching!')}
React Query also exports a handy useIsFetching
hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
client.setQueryDefaults
setQueryDefaults
is a synchronous method to set default options for a specific query. If the query does not exist yet it will create it.
client.setQueryDefaults('posts', fetchPosts)function Component() {const { data } = useQuery('posts')}
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersQueryCache
The QueryCache
is the backbone of React Query that manages all of the state, caching, lifecycle and magic of every query. It supports relatively unrestricted, but safe, access to manipulate query's as you need.
import { QueryCache } from 'react-query'const cache = new QueryCache()const query = cache.find('posts')
Its available methods are:
cache.find
find
is a slightly more advanced synchronous method that can be used to get an existing query instance from the cache. This instance not only contains all the state for the query, but all of the instances, and underlying guts of the query as well. If the query does not exist, undefined
will be returned.
Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios (eg. Looking at the query.state.updatedAt timestamp to decide whether a query is fresh enough to be used as an initial value)
const query = cache.find(queryKey)
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersReturns
Query
cache.findAll
findAll
is even more advanced synchronous method that can be used to get existing query instances from the cache that partially match query key. If queries do not exist, empty array will be returned.
Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios
const queries = cache.findAll(queryKey)
Options
queryKey?: QueryKey
: Query Keysfilters?: QueryFilters
: Query FiltersReturns
Query[]
client.subscribe
The subscribe
method can be used to subscribe to the query cache as a whole and be informed of safe/known updates to the cache like query states changing or queries being updated, added or removed
const callback = (cache, query) => {}const unsubscribe = cache.subscribe(callback)
Options
callback: (cache, query?) => void
query.setState
, client.removeQueries
, etc). Out of scope mutations to the cache are not encouraged and will not fire subscription callbacksquery
will be passed as the second argument to the callbackReturns
unsubscribe: Function => void
cache.clear
The clear
method can be used to clear the cache entirely and start fresh.
cache.clear()
useQueryClient
The useQueryClient
hook returns the current QueryClient
instance.
import { useQueryClient } from 'react-query'const client = useQueryClient()
useIsFetching
useIsFetching
is an optional hook that returns the number
of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators).
import { useIsFetching } from 'react-query'const isFetching = useIsFetching()
Returns
isFetching: number
number
of the queries that your application is currently loading or fetching in the background.QueryClientProvider
Use the QueryClientProvider
component to connect a QueryClient
to your application:
import { QueryClient, QueryClientProvider, QueryCache } from 'react-query'const cache = new QueryCache()const client = new QueryClient({ cache })function App() {return <QueryClientProvider client={client}>...</QueryClientProvider>}
QueryErrorResetBoundary
When using suspense or useErrorBoundaries in your queries, you need a way to let queries know that you want to try again when re-rendering after some error occured. With the QueryErrorResetBoundary
component you can reset any query errors within the boundaries of the component.
import { QueryErrorResetBoundary } from 'react-query'import { ErrorBoundary } from 'react-error-boundary'const App: React.FC = () => (<QueryErrorResetBoundary>{({ reset }) => (<ErrorBoundaryonReset={reset}fallbackRender={({ resetErrorBoundary }) => (<div>There was an error!<Button onClick={() => resetErrorBoundary()}>Try again</Button></div>)}><Page /></ErrorBoundary>)}</QueryErrorResetBoundary>)
useQueryErrorResetBoundary
This hook will reset any query errors within the closest QueryErrorResetBoundary
. If there is no boundary defined it will reset them globally:
import { useQueryErrorResetBoundary } from 'react-query'import { ErrorBoundary } from 'react-error-boundary'const App: React.FC = () => {const { reset } = useQueryErrorResetBoundary()return (<ErrorBoundaryonReset={reset}fallbackRender={({ resetErrorBoundary }) => (<div>There was an error!<Button onClick={() => resetErrorBoundary()}>Try again</Button></div>)}><Page /></ErrorBoundary>)}
setConsole
setConsole
is an optional utility function that allows you to replace the console
interface used to log errors. By default, the window.console
object is used. If no global console
object is found in the environment, nothing will be logged.
import { setConsole } from 'react-query'import { printLog, printWarn, printError } from 'custom-logger'setConsole({log: printLog,warn: printWarn,error: printError,})
Options
console: Object
log
, warn
, and error
methods.hydration/dehydrate
dehydrate
creates a frozen representation of a cache
that can later be hydrated with useHydrate
, hydrate
or Hydrate
. This is useful for passing prefetched queries from server to client or persisting queries to localstorage. It only includes currently successful queries by default.
import { dehydrate } from 'react-query/hydration'const dehydratedState = dehydrate(cache, {shouldDehydrate,})
Options
cache: QueryCache
cache
that should be dehydratedshouldDehydrate: (query: Query) => boolean
true
to include this query in dehydration, or false
otherwiseshouldDehydrate: () => true
to include all queriesReturns
dehydratedState: DehydratedState
cache
at a later pointhydration/hydrate
hydrate
adds a previously dehydrated state into a cache
. If the queries included in dehydration already exist in the cache, hydrate
does not overwrite them.
import { hydrate } from 'react-query/hydration'hydrate(cache, dehydratedState)
Options
cache: QueryCache
cache
to hydrate the state intodehydratedState: DehydratedState
hydration/useHydrate
useHydrate
adds a previously dehydrated state into the cache
returned by useQueryCache
.
import { useHydrate } from 'react-query/hydration'useHydrate(dehydratedState)
Options
dehydratedState: DehydratedState
hydration/Hydrate
hydration/Hydrate
does the same thing as useHydrate
but exposed as a component.
import { Hydrate } from 'react-query/hydration'function App() {return <Hydrate state={dehydratedState}>...</Hydrate>}
Options
state: DehydratedState
The latest TanStack news, articles, and resources, sent to your inbox.