API Slices: React Hooks#

Hooks Overview#

The 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:

import { createApi } from 'reduxjs/toolkit/query/react'

If you have used the React-specific version of createApi, the generated Api slice structure will also contain a set of React hooks. These 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:

Generated React Hook names
// Hooks attached to the endpoint definition
const { data } = api.endpoints.getPosts.useQuery()
const { data } = api.endpoints.updatePost.useMutation()
// Same hooks, but given unique names and attached to the API slice object
const { data } = api.useGetPostsQuery()
const [updatePost] = api.useUpdatePostMutation()

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 React-specific version of createApi also generates a usePrefetch hook, attached to the Api object, which can be used to initiate fetching data ahead of time.

useQuery#

Signature#

type UseQuery = (arg: any, options?: UseQueryOptions) => UseQueryResult
type UseQueryOptions = {
pollingInterval?: number
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
selectFromResult?: QueryStateSelector
}
type UseQueryResult<T> = {
// Base query state
status: 'uninitialized' | 'pending' | 'fulfilled' | 'rejected' // @deprecated - A string describing the query state
originalArgs?: unknown // Arguments passed to the query
data?: T // Returned result if present
error?: unknown // Error result if present
requestId?: string // A string generated by RTK Query
endpointName?: string // The name of the given endpoint for the query
startedTimeStamp?: number // Timestamp for when the query was initiated
fulfilledTimeStamp?: number // Timestamp for when the query was completed
isUninitialized: false // Query has not started yet.
isLoading: false // Query is currently loading for the first time. No data yet.
isFetching: false // Query is currently fetching, but might have data from an earlier request.
isSuccess: false // Query has data from a successful load.
isError: false // Query is currently in an "error" state.
refetch: () => void // A function to force refetch the query
}
  • Parameters
    • arg: The query argument to be used in constructing the query itself, and as a cache key for the query
    • options: 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

Description#

A React hook that triggers fetches of data from an endpoint, and subscribes the component to read 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.

useMutation#

Signature#

type UseMutation<Definition> = (
UseMutationStateOptions<Definition>
) => [UseMutationTrigger<Definition>, UseMutationResult<Definition> | SelectedUseMutationResult];
type UseMutationStateOptions<Definition> = {
// A method to determine the contents of `UseMutationResult`
selectFromResult?: (state, defaultMutationStateSelector) => SelectedUseMutationResult extends Record<string, any>
}
type UseMutationTrigger<Definition> = (
arg: ArgTypeFrom<Definition>
) => Promise<{ data: ResultTypeFrom<Definition> } | { error: BaseQueryError | SerializedError }> & {
requestId: string; // A string generated by RTK Query
abort: () => void; // A method to cancel the mutation promise
unwrap: () => Promise<ResultTypeFrom<Definition>>; // A method to unwrap the mutation call and provide the raw response/error
unsubscribe: () => void; // A method to manually unsubscribe from the mutation call
};
type UseMutationResult<Definition> = {
data?: ResultTypeFrom<Definition>; // Returned result if present
endpointName?: string; // The name of the given endpoint for the mutation
error?: any; // Error result if present
fulfilledTimestamp?: number; // Timestamp for when the mutation was completed
isError: boolean; // Mutation is currently in an "error" state
isLoading: boolean; // Mutation has been fired and is awaiting a response
isSuccess: boolean; // Mutation has data from a successful call
isUninitialized: boolean; // Mutation has not been fired yet
originalArgs?: ArgTypeFrom<Definition>; // Arguments passed to the latest mutation call
startedTimeStamp?: number; // Timestamp for when the latest mutation was initiated
};
tip

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.

Passing a completely empty object will prevent the hook from causing a re-render at all, e.g.

selectFromResult: () => ({})
  • 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 behaviour of the promise.
    • mutationState: a query status object containing the current loading state and metadata about the request

Description#

A 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.

useQueryState#

TBD

useQuerySubscription#

TBD

useLazyQuery#

TBD

useLazyQuerySubscription#

TBD

usePrefetch#

TBD