
useQueryconst {data,error,failureCount,isError,isFetchedAfterMount,isFetching,isIdle,isLoading,isPreviousData,isStale,isSuccess,refetch,remove,status,} = useQuery(queryKey, queryFn?, {cacheTime,enabled,initialData,initialStale,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,config,})
Options
queryKey: String | any[]enabled is not set to false).queryFn: Function(variables) => Promise(data/error)enabled: Boolean | unknownfalse to disable this query from automatically running.retry: Boolean | Int | Function(failureCount, error) => shouldRetry | Booleanfalse, failed queries will not retry by default.true, failed queries will retry infinitely.Int, e.g. 3, failed queries will retry until the failed query count meets that number.retryDelay: Function(retryAttempt: Int) => IntretryAttempt 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: Int | InfinityInfinity, query will never go stalecacheTime: Int | InfinityInfinity, will disable garbage collectionrefetchInterval: false | IntegerrefetchIntervalInBackground: Booleantrue, queries that are set to continuously refetch with a refetchInterval will continue to refetch while their tab/window is in the backgroundrefetchOnMount: boolean | "always"truetrue, the query will refetch on mount if the data is stale.false, will disable additional instances of a query to trigger background refetches."always", the query will always refetch on mount.refetchOnWindowFocus: boolean | "always"truetrue, 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"truetrue, 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: Booleanfalse to only re-render when there are changes to data or error.true.onSuccess: Function(data) => dataonError: Function(err) => voidonSettled: Function(data, error) => datasuspense: Booleantrue to enable suspense mode.true, useQuery will suspend when status === 'loading'true, useQuery will throw runtime errors when status === 'error'initialData: any | Function() => anyinitialStale: Boolean | Function() => BooleaninitialData provided as stale and will likely cause it to be refetched on mountinitialStale value. This can be useful if your initialStale value is costly to calculate.keepPreviousData: Booleanfalsedata will be kept when fetching new data because the query key changed.queryFnParamsFilter: Function(args) => filteredArgsqueryFn.queryFnParamsFilter: args => args.slice(1).structuralSharing: Booleantruefalse, structural sharing between query results will be disabled.Returns
status: Stringidle 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 === trueerror 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: Booleanstatus variable above, provided for convenience.isLoading: Booleanstatus variable above, provided for convenience.isSuccess: Booleanstatus variable above, provided for convenience.isError: Booleanstatus variable above, provided for convenience.data: Anyundefined.error: null | ErrornullisStale: Booleantrue if the cache data is stale.isPreviousData: Booleantrue when keepPreviousData is set and data from the previous query is returned.isFetchedAfterMount: Booleantrue if the query has been fetched after the component mounted.isFetching: Booleantrue so long as manual is set to falsetrue if the query is currently fetching, including background fetching.failureCount: Integer0 when the query succeeds.refetch: Function({ throwOnError }) => Promise<TResult | undefined>throwOnError: true optionremove: Function() => voidusePaginatedQueryconst {data = undefined,resolvedData,latestData,...queryInfo} = usePaginatedQuery(queryKey, queryFn, options)
Options
The options for usePaginatedQuery are identical to the useQuery hook
Returns
The returned properties for usePaginatedQuery are identical to the useQuery hook, with the addition of the following:
data: undefineddata property is not used for paginated queries and is replaced by the resolvedData and latestData options below.resolvedData: Anyundefined.latestData: Anyundefined.undefineduseInfiniteQueryconst 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: Function(lastPage, allPages) => fetchMoreVariable | BooleanReturns
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: Function(fetchMoreVariableOverride) => Promise<TResult | 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: Booleanpaginated mode, this will be true if there is more data to be fetched (known via the required getFetchMore option function).useMutationconst [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: Function(variables) => Promisevariables is an object that mutate will pass to your mutationFnonMutate: Function(variables) => Promise | snapshotValueonError and onSettled functions in the event of a mutation failure and can be useful for rolling back optimistic updates.onSuccess: Function(data, variables) => Promise | undefinedmutate-level onSuccess handler (if it is defined)onError: Function(err, variables, onMutateValue) => Promise | undefinedmutate-level onError handler (if it is defined)onSettled: Function(data, error, variables, onMutateValue) => Promise | undefinedmutate-level onSettled handler (if it is defined)throwOnErrorfalsetrue if failed mutations should re-throw errors from the mutation function to the mutate function.useErrorBoundaryuseErrorBoundary value, which is falseReturns
mutate: Function(variables, { onSuccess, onSettled, onError, throwOnError }) => Promisevariables: anymutationFn.useMutation hook.useMutation-level options.status: Stringidle 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 statusdata: undefined | Anyundefinederror: null | Errorreset: Function() => voidQueryCacheThe 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 queryCache = new QueryCache({defaultConfig: {queries: {staleTime: Infinity,},},})
Its available properties and methods are:
fetchQueryprefetchQuerygetQueryDatasetQueryDatarefetchQueriesinvalidateQueriescancelQueriesremoveQueriesgetQuerygetQueriesisFetchingsubscribeclearOptions
defaultConfig: QueryQueryConfigqueryCache.fetchQueryfetchQuery 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.
try {const data = await queryCache.fetchQuery(queryKey, queryFn)} catch (error) {console.log(error)}
Returns
Promise<TResult>queryCache.prefetchQueryprefetchQuery is an asynchronous method that can be used to fetch and cache a query response before it is needed or rendered with useQuery and friends.
force: true option in the options objectThe difference between using
prefetchQueryandsetQueryDatais thatprefetchQueryis async and will ensure that duplicate requests for this query are not created withuseQueryinstances for the same query are rendered while the data is fetching.
await queryCache.prefetchQuery(queryKey, queryFn)
To pass options like force or throwOnError, use the fourth options object:
await queryCache.prefetchQuery(queryKey, queryFn, config, {force: true,throwOnError: true,})
You can even use it with a default queryFn in your config!
await queryCache.prefetchQuery(queryKey)
Options
The options for prefetchQuery are exactly the same as those of useQuery with the exception of the last options object:
force: Booleantrue if you want prefetchQuery to fetch the data even if the data exists and is NOT stale.throwOnError: Booleantrue if you want prefetchQuery to throw an error when it encounters errors.Returns
Promise<TResult | undefined>throwOnError option to true.queryCache.getQueryDatagetQueryData 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 = queryCache.getQueryData(queryKey)
Options
queryKey: QueryKeyReturns
data: any | undefinedundefined if the query does not exist.queryCache.setQueryDatasetQueryData 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 and immediately be marked as stale. 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
setQueryDataandprefetchQueryis thatsetQueryDatais 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 useprefetchQueryto handle the asynchronous fetch.
queryCache.setQueryData(queryKey, updater, config)
Options
queryKey: QueryKeyupdater: Any | Function(oldData) => newDataconfig: objectuseQueryUsing 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)
queryCache.refetchQueriesThe refetchQueries method can be used to refetch queries based on certain conditions.
Examples:
// refetch all queries:await queryCache.refetchQueries()// refetch all stale queries:await queryCache.refetchQueries([], { stale: true })// refetch all stale and active queries:await queryCache.refetchQueries([], { stale: true, active: true })// refetch all queries partially matching a query key:await queryCache.refetchQueries(['posts'])// refetch all queries exactly matching a query key:await queryCache.refetchQueries(['posts', 1], { exact: true })
Options
queryKeyOrPredicateFn can either be a Query Key or a FunctionqueryKey: QueryKey'todos', it would match queries with the todos, ['todos'], and ['todos', 5]. See Query Keys for more information.query => booleanfound.exact option has no effect when using a functionexact?: booleanexact: true option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!active?: booleantrue it will refetch active queries.false it will refetch inactive queries.stale?: booleantrue it will match on stale queries.false it will match on fresh queries.throwOnError?: booleantrue, 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
queryCache.invalidateQueriesThe invalidateQueries method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as stale and active queries are refetched in the background.
refetchActive: false option.refetchInactive: true optionconst queries = queryCache.invalidateQueries(inclusiveQueryKeyOrPredicateFn, {exact,throwOnError,refetchActive = true,refetchInactive = false})
Options
queryKeyOrPredicateFn can either be a Query Key or a functionqueryKey: QueryKey'todos', it would match queries with the todos, ['todos'], and ['todos', 5]. See Query Keys for more information.Function(query) => Booleanfound.exact option has no effect with using a functionexact: Booleanexact: true option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!throwOnError: Booleantrue, this function will throw if any of the query refetch tasks fail.refetchActive: Booleantruefalse, queries that match the refetch predicate and are actively being rendered via useQuery and friends will NOT be refetched in the background, and only marked as stale.refetchInactive: Booleanfalsetrue, queries that match the refetch predicate and are not being rendered via useQuery and friends will be both marked as stale and also refetched in the backgroundReturns
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
queryCache.cancelQueriesThe 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.
const queries = queryCache.cancelQueries(queryKeyOrPredicateFn, {exact,})
Options
queryKeyOrPredicateFn can either be a Query Key or a functionqueryKey'todos', it would match queries with the todos, ['todos'], and ['todos', 5]. See Query Keys for more information.Function(query) => Booleanfound.exact option has no effect with using a functionexact: Booleanexact: true option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!Returns
This function does not return anything
queryCache.removeQueriesThe 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.
queryCache.removeQueries(queryKeyOrPredicateFn, {exact,})
Options
queryKeyOrPredicateFn can either be a Query Key or a functionqueryKey'todos', it would match queries with the todos, ['todos'], and ['todos', 5]. See Query Keys for more information.Function(query) => Booleanfound.exact option has no effect with using a functionexact: Booleanexact: true option to return only the query with the exact query key you have passed. Remember to destructure it out of the array!Returns
This function does not return anything
queryCache.getQuerygetQuery is a slightly more advanced synchronous function that can be used to get an existing query object from the cache. This object 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 = queryCache.getQuery(queryKey)
Options
queryKey: QueryKeyReturns
query: QueryObjectqueryCache.getQueriesgetQueries is even more advanced synchronous function that can be used to get existing query objects 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 = queryCache.getQueries(queryKey)
Options
queryKey: QueryKeyReturns
queries: QueryObject[]queryCache.isFetchingThis isFetching property is 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 (queryCache.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.
queryCache.subscribeThe 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 = queryCache.subscribe(callback)
Options
callback: Function(queryCache, query?) => voidquery.setState, queryCache.removeQueries, etc). Out of scope mutations to the queryCache are not encouraged and will not fire subscription callbacksquery will be passed as the second argument to the callbackReturns
unsubscribe: Function => voidqueryCache.clearThe clear method can be used to clear the queryCache entirely and start fresh.
queryCache.clear()
Returns
queries: Array<Query>makeQueryCacheThe makeQueryCache factory function has been deprecated in favor of new QueryCache().
useQueryCacheThe useQueryCache hook returns the current queryCache instance.
import { useQueryCache } from 'react-query'const queryCache = useQueryCache()
useIsFetchinguseIsFetching 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: Intnumber of the queries that your application is currently loading or fetching in the background.ReactQueryConfigProviderReactQueryConfigProvider is an optional provider component and can be used to define defaults for all instances of useQuery within it's sub-tree:
import {QueryCache,ReactQueryCacheProvider,ReactQueryConfigProvider,} from 'react-query'const queryCache = new QueryCache({defaultConfig: {queries: {suspense: false,queryKeySerializerFn: defaultQueryKeySerializerFn,queryFn,enabled: true,retry: 3,retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),staleTime: 0,cacheTime: 5 * 60 * 1000,refetchOnWindowFocus: true,refetchInterval: false,queryFnParamsFilter: identity,refetchOnMount: true,isDataEqual: deepEqual,onError: noop,onSuccess: noop,onSettled: noop,useErrorBoundary: false, // falls back to suspense},mutations: {suspense: false,throwOnError: false,onMutate: noop,onError: noop,onSuccess: noop,onSettled: noop,useErrorBoundary: false, // falls back to suspense},},})const overrides = {queries: {suspense: true,},mutations: {suspense: true,},}function App() {return (<ReactQueryCacheProvider queryCache={queryCache}>...<ReactQueryConfigProvider config={overrides}>...</ReactQueryConfigProvider></ReactQueryCacheProvider>)}
Options
config: ObjectuseQuery hook and the useMutation hook.ReactQueryCacheProviderThe query cache can be connected to React with the ReactQueryCacheProvider. This component puts the cache on the context, which enables you to access it from anywhere in your component tree.
import { ReactQueryCacheProvider, QueryCache } from 'react-query'const queryCache = new QueryCache()function App() {return (<ReactQueryCacheProvider queryCache={queryCache}>...</ReactQueryCacheProvider>)}
Options
queryCache: QueryCacheReactQueryErrorResetBoundaryWhen 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 ReactQueryErrorResetBoundary component you can reset any query errors within the boundaries of the component.
import { ReactQueryErrorResetBoundary } from 'react-query'import { ErrorBoundary } from 'react-error-boundary'const App: React.FC = () => (<ReactQueryErrorResetBoundary>{({ reset }) => (<ErrorBoundaryonReset={reset}fallbackRender={({ resetErrorBoundary }) => (<div>There was an error!<Button onClick={() => resetErrorBoundary()}>Try again</Button></div>)}><Page /></ErrorBoundary>)}</ReactQueryErrorResetBoundary>)
useErrorResetBoundaryThis hook will reset any query errors within the closest ReactQueryErrorResetBoundary. If there is no boundary defined it will reset them globally:
import { useErrorResetBoundary } from 'react-query'import { ErrorBoundary } from 'react-error-boundary'const App: React.FC = () => {const { reset } = useErrorResetBoundary()return (<ErrorBoundaryonReset={reset}fallbackRender={({ resetErrorBoundary }) => (<div>There was an error!<Button onClick={() => resetErrorBoundary()}>Try again</Button></div>)}><Page /></ErrorBoundary>)}
setConsolesetConsole 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: Objectlog, warn, and error methods.hydration/dehydratedehydrate creates a frozen representation of a queryCache 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(queryCache, {shouldDehydrate,})
Options
queryCache: QueryCachequeryCache that should be dehydratedshouldDehydrate: Function(query: Query) => Booleantrue to include this query in dehydration, or false otherwiseshouldDehydrate: () => true to include all queriesReturns
dehydratedState: DehydratedStatequeryCache at a later pointhydration/hydratehydrate adds a previously dehydrated state into a queryCache. If the queries included in dehydration already exist in the cache, hydrate does not overwrite them.
import { hydrate } from 'react-query/hydration'hydrate(queryCache, dehydratedState)
Options
queryCache: QueryCachequeryCache to hydrate the state intodehydratedState: DehydratedStatehydration/useHydrateuseHydrate adds a previously dehydrated state into the queryCache returned by useQueryCache.
import { useHydrate } from 'react-query/hydration'useHydrate(dehydratedState)
Options
dehydratedState: DehydratedStatehydration/Hydratehydration/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: DehydratedStateThe latest TanStack news, articles, and resources, sent to your inbox.