#
API Slices: React Hooks#
Hooks OverviewThe core RTK Query createApi
method is UI-agnostic, in the same way that the Redux core library and Redux Toolkit are UI-agnostic. They are all plain JS logic that can be used anywhere.
However, RTK Query also provides the ability to auto-generate React hooks for each of your endpoints. Since this specifically depends on React itself, RTK Query provides an alternate entry point that exposes a customized version of createApi
that includes that functionality:
If you have used the React-specific version of createApi
, the generated Api
slice structure will also contain a set of React hooks. The primary endpoint hooks are available as api.endpoints[endpointName].useQuery
or api.endpoints[endpointName].useMutation
, matching how you defined that endpoint.
The same hooks are also added to the Api
object itself, and given auto-generated names based on the endpoint name and query/mutation type.
For example, if you had endpoints for getPosts
and updatePost
, these options would be available:
The general format is use(Endpointname)(Query|Mutation)
- use
is prefixed, the first letter of your endpoint name is capitalized, then Query
or Mutation
is appended depending on the type.
The full list of hooks generated in the React-specific version of createApi
is as follows:
useQuery
(endpoint-specific)useMutation
(endpoint-specific)useQueryState
(endpoint-specific)useQuerySubscription
(endpoint-specific)useLazyQuery
(endpoint-specific)useLazyQuerySubscription
(endpoint-specific)usePrefetch
(endpoint-agnostic)
For the example above, the full set of generated hooks for the api would be like so:
#
Feature ComparisonThe provided hooks have a degree of feature overlap in order to provide options optimized for a given situation. The table below provides a comparison of the core features for each hook.
useQuery
#
#
Signature- Parameters
arg
: The query argument to be used in constructing the query itself, and as a cache key for the query. You can also pass inskipToken
here as an alternative way of skipping the query, see skipTokenoptions
: A set of options that control the fetching behavior of the hook
- Returns
- A query result object containing the current loading state, the actual data or error returned from the API call, metadata about the request, and a function to
refetch
the data. Can be customized withselectFromResult
- A query result object containing the current loading state, the actual data or error returned from the API call, metadata about the request, and a function to
#
DescriptionA React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
This hook combines the functionality of both useQueryState
and useQuerySubscription
together, and is intended to be used in the majority of situations.
Features
- Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
- 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
- Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
- Returns the latest request status and cached data from the Redux store
- Re-renders as the request status changes and data becomes available
skipToken
#
Can be passed into useQuery
, useQueryState
or useQuerySubscription
instead of the query argument to get the same effect as if setting
skip: true
in the query options.
Useful for scenarios where a query should be skipped when arg
is undefined
and TypeScript complains about it because arg
is not allowed to be passed
in as undefined
, such as
If passed directly into a query or mutation selector, that selector will always return an uninitialized state.
See also Skipping queries with TypeScript using skipToken
useMutation
#
#
Signaturetip
The generated UseMutation
hook will cause a component to re-render by default after the trigger callback is fired, as it affects the properties of the result. If you want to call the trigger but don't care about subscribing to the result with the hook, you can use the selectFromResult
option to limit the properties that the hook cares about.
Returning a completely empty object will mean that any individual mutation call will cause only one re-render at most, e.g.
Parameters
options
: A set of options that control the subscription behavior of the hook
Returns: A tuple containing:
trigger
: A function that triggers an update to the data based on the provided argument. The trigger function returns a promise with the properties shown above that may be used to handle the behavior of the promisemutationState
: A query status object containing the current loading state and metadata about the request, or the values returned by theselectFromResult
option where applicable
#
DescriptionA React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
Features
- Manual control over firing a request to alter data on the server or possibly invalidate the cache
- 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
- Returns the latest request status and cached data from the Redux store
- Re-renders as the request status changes and data becomes available
useQueryState
#
#
SignatureParameters
arg
: The argument passed to the query defined in the endpoint. You can also pass inskipToken
here as an alternative way of skipping the selection, see skipTokenoptions
: A set of options that control the return value for the hook
Returns
- A query result object containing the current loading state, the actual data or error returned from the API call and metadata about the request. Can be customized with
selectFromResult
- A query result object containing the current loading state, the actual data or error returned from the API call and metadata about the request. Can be customized with
#
DescriptionA React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
Note that this hook does not trigger fetching new data. For that use-case, see useQuery
or useQuerySubscription
.
Features
- Returns the latest request status and cached data from the Redux store
- Re-renders as the request status changes and data becomes available
useQuerySubscription
#
#
SignatureParameters
arg
: The argument passed to the query defined in the endpoint. You can also pass inskipToken
here as an alternative way of skipping the query, see skipTokenoptions
: A set of options that control the fetching behaviour of the hook
Returns
- An object containing a function to
refetch
the data
- An object containing a function to
#
DescriptionA React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
Note that this hook does not return a request status or cached data. For that use-case, see useQuery
or useQueryState
.
Features
- Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
- 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
- Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
useLazyQuery
#
#
SignatureParameters
options
: A set of options that control the fetching behavior and returned result value of the hook. Options affecting fetching behavior will only have an effect after the lazy query has been triggered at least once.
Returns: A tuple containing:
trigger
: A function that fetches the corresponding data for the endpoint when calledresult
: A query result object containing the current loading state, the actual data or error returned from the API call and metadata about the request. Can be customized withselectFromResult
lastPromiseInfo
: An object containing the last argument used to call the trigger function
#
DescriptionA React hook similar to useQuery
, but with manual control over when the data fetching occurs.
This hook includes the functionality of useLazyQuerySubscription
.
Features
- Manual control over firing a request to retrieve data
- 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
- Returns the latest request status and cached data from the Redux store
- Re-renders as the request status changes and data becomes available
- Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
useLazyQuerySubscription
#
#
SignatureParameters
options
: A set of options that control the fetching behavior of the hook. The options will only have an effect after the lazy query has been triggered at least once.
Returns: A tuple containing:
trigger
: A function that fetches the corresponding data for the endpoint when calledlastArg
: The last argument used to call the trigger function
#
DescriptionA React hook similar to useQuerySubscription
, but with manual control over when the data fetching occurs.
Note that this hook does not return a request status or cached data. For that use-case, see useLazyQuery
.
Features
- Manual control over firing a request to retrieve data
- 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
- Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
usePrefetch
#
#
SignatureParameters
endpointName
: The name of the endpoint to prefetch data foroptions
: A set of options that control whether the prefetch request should occur
Returns
- A
prefetch
callback that when called, will initiate fetching the data for the provided endpoint
- A
#
DescriptionA React hook which can be used to initiate fetching data ahead of time.
#
Features- Manual control over firing a request to retrieve data