Skip to main content

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

Generated React Hook names
// Hooks attached to the endpoint definition
const { data } = api.endpoints.getPosts.useQuery()
const [updatePost, { data }] = api.endpoints.updatePost.useMutation()

// Same hooks, but given unique names and attached to the API slice object
const { data } = api.useGetPostsQuery()
const [updatePost, { data }] = 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.

RTK Query provides additional hooks for more advanced use-cases, although not all are generated directly on the Api object as well. The full list of hooks generated in the React-specific version of createApi is as follows:

For the example above, the full set of generated hooks for the api would be like so:

Generated React Hooks
/* Hooks attached to the `getPosts` query endpoint definition */
api.endpoints.getPosts.useQuery(arg, options)
api.endpoints.getPosts.useQueryState(arg, options)
api.endpoints.getPosts.useQuerySubscription(arg, options)
api.endpoints.getPosts.useLazyQuery(options)
api.endpoints.getPosts.useLazyQuerySubscription(options)

/* Hooks attached to the `updatePost` mutation endpoint definition */
api.endpoints.updatePost.useMutation(options)

/* Hooks attached to the `Api` object */
api.useGetPostsQuery(arg, options) // same as api.endpoints.getPosts.useQuery
api.useLazyGetPostsQuery(options) // same as api.endpoints.getPosts.useLazyQuery
api.useUpdatePostMutation(options) // same as api.endpoints.updatePost.useMutation
api.usePrefetch(endpointName, options)

Feature Comparison

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

Feature
Automatically triggers query requests✔️✔️
Allows manually triggering query requests✔️✔️✔️✔️✔️
Allows manually triggering mutation requests✔️
Subscribes a component to keep cached data in the store✔️✔️✔️✔️✔️
Returns request status and cached data from the store✔️✔️✔️✔️
Re-renders as request status and data become available✔️✔️✔️✔️
Accepts polling/re-fetching options to trigger automatic re-fetches✔️✔️✔️✔️

useQuery

Accessing a useQuery hook
const useQueryResult = api.endpoints.getPosts.useQuery(arg, options)
// or
const useQueryResult = api.useGetPostsQuery(arg, options)

Signature

type UseQuery = (
arg: any | SkipToken,
options?: UseQueryOptions
) => UseQueryResult

type UseQueryOptions = {
pollingInterval?: number
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseQueryResult<T> = {
// Base query state
originalArgs?: unknown // Arguments passed to the query
data?: T // The latest returned result regardless of hook arg, if present
currentData?: T // The latest returned result for the current hook arg, 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

// Derived request status booleans
isUninitialized: boolean // Query has not started yet.
isLoading: boolean // Query is currently loading for the first time. No data yet.
isFetching: boolean // Query is currently fetching, but might have data from an earlier request.
isSuccess: boolean // Query has data from a successful load.
isError: boolean // 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. You can also pass in skipToken here as an alternative way of skipping the query, see skipToken
    • 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. Can be customized with selectFromResult

Description

A 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

will error if the query argument is not allowed to be undefined
useSomeQuery(arg, { skip: !!arg })
using skipToken instead
useSomeQuery(arg ?? skipToken)

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

Accessing a useMutation hook
const useMutationResult = api.endpoints.updatePost.useMutation(options)
// or
const useMutationResult = api.useUpdatePostMutation(options)

Signature

type UseMutation = (
options?: UseMutationStateOptions
) => [UseMutationTrigger, UseMutationResult | SelectedUseMutationResult]

type UseMutationStateOptions = {
// A method to determine the contents of `UseMutationResult`
selectFromResult?: (result: UseMutationStateDefaultResult) => any
// A string used to enable shared results across hook instances which have the same key
fixedCacheKey?: string
}

type UseMutationTrigger<T> = (arg: any) => Promise<
{ data: T } | { error: BaseQueryError | SerializedError }
> & {
requestId: string // A string generated by RTK Query
abort: () => void // A method to cancel the mutation promise
unwrap: () => Promise<T> // A method to unwrap the mutation call and provide the raw response/error
reset: () => void // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state
}

type UseMutationResult<T> = {
// Base query state
originalArgs?: unknown // Arguments passed to the latest mutation call. Not available if using the `fixedCacheKey` option
data?: T // Returned result if present
error?: unknown // Error result if present
endpointName?: string // The name of the given endpoint for the mutation
fulfilledTimestamp?: number // Timestamp for when the mutation was completed

// Derived request status booleans
isUninitialized: boolean // Mutation has not been fired yet
isLoading: boolean // Mutation has been fired and is awaiting a response
isSuccess: boolean // Mutation has data from a successful call
isError: boolean // Mutation is currently in an "error" state
startedTimeStamp?: number // Timestamp for when the latest mutation was initiated

reset: () => void // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state
}
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.

Returning a completely empty object will mean that any individual mutation call will cause only one re-render at most, e.g.

selectFromResult: () => ({})
  • Parameters

    • options: A set of options that control the subscription behavior of the hook:
      • selectFromResult: A callback that can be used to customize the mutation result returned as the second item in the tuple
      • fixedCacheKey: An optional string used to enable shared results across hook instances
  • 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 promise
    • mutationState: A query status object containing the current loading state and metadata about the request, or the values returned by the selectFromResult option where applicable. Additionally, this object will contain
      • a reset method to reset the hook back to it's original state and remove the current result from the cache
      • an originalArgs property that contains the argument passed to the last call of the trigger function.

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.

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

Accessing a useQuery hook
const useQueryStateResult = api.endpoints.getPosts.useQueryState(arg, options)

Signature

type UseQueryState = (
arg: any | SkipToken,
options?: UseQueryStateOptions
) => UseQueryStateResult | SelectedQueryStateResult

type UseQueryStateOptions = {
skip?: boolean
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseQueryStateResult<T> = {
// Base query state
originalArgs?: unknown // Arguments passed to the query
data?: T // The latest returned result regardless of hook arg, if present
currentData?: T // The latest returned result for the current hook arg, 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.
}
  • Parameters

    • arg: The argument passed to the query defined in the endpoint. You can also pass in skipToken here as an alternative way of skipping the selection, see skipToken
    • options: 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

Description

A 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

Accessing a useQuerySubscription hook
const { refetch } = api.endpoints.getPosts.useQuerySubscription(arg, options)

Signature

type UseQuerySubscription = (
arg: any | SkipToken,
options?: UseQuerySubscriptionOptions
) => UseQuerySubscriptionResult

type UseQuerySubscriptionOptions = {
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
pollingInterval?: number
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
}

type UseQuerySubscriptionResult = {
refetch: () => void // A function to force refetch the query
}
  • Parameters

    • arg: The argument passed to the query defined in the endpoint. You can also pass in skipToken here as an alternative way of skipping the query, see skipToken
    • options: A set of options that control the fetching behaviour of the hook
  • Returns

    • An object containing a function to refetch the data

Description

A 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

Accessing a useLazyQuery hook
const [trigger, result, lastPromiseInfo] =
api.endpoints.getPosts.useLazyQuery(options)
// or
const [trigger, result, lastPromiseInfo] = api.useLazyGetPostsQuery(options)

Signature

type UseLazyQuery = (
options?: UseLazyQueryOptions
) => [UseLazyQueryTrigger, UseQueryStateResult, UseLazyQueryLastPromiseInfo]

type UseLazyQueryOptions = {
pollingInterval?: number
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseLazyQueryTrigger<T> = (arg: any, preferCacheValue?: boolean) => Promise<
QueryResultSelectorResult
> & {
arg: unknown // Whatever argument was provided to the query
requestId: string // A string generated by RTK Query
subscriptionOptions: SubscriptionOptions // The values used for the query subscription
abort: () => void // A method to cancel the query promise
unwrap: () => Promise<T> // A method to unwrap the query call and provide the raw response/error
unsubscribe: () => void // A method used to manually unsubscribe from the query results
refetch: () => void // A method used to re-run the query. In most cases when using a lazy query, you will never use this and should prefer to call the trigger again.
updateSubscriptionOptions: (options: SubscriptionOptions) () => void // A method used to update the subscription options (eg. pollingInterval)
}

type UseQueryStateResult<T> = {
// Base query state
originalArgs?: unknown // Arguments passed to the query
data?: T // The latest returned result regardless of trigger arg, if present
currentData?: T // The latest returned result for the trigger arg, 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.
}

type UseLazyQueryLastPromiseInfo = {
lastArg: any
}
  • Parameters

    • 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 called
    • result: 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
    • lastPromiseInfo: An object containing the last argument used to call the trigger function

Description

A 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

Note

When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set preferCacheValue(the second argument to the function) as true if you want it to immediately return a cached value if one exists.

useLazyQuerySubscription

Accessing a useLazyQuerySubscription hook
const [trigger, lastArg] =
api.endpoints.getPosts.useLazyQuerySubscription(options)

Signature

type UseLazyQuerySubscription = (
options?: UseLazyQuerySubscriptionOptions
) => [UseLazyQuerySubscriptionTrigger, LastArg]

type UseLazyQuerySubscriptionOptions = {
pollingInterval?: number
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
}

type UseLazyQuerySubscriptionTrigger = (
arg: any,
preferCacheValue?: boolean
) => void
  • Parameters

    • 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 called
    • lastArg: The last argument used to call the trigger function

Description

A 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

Accessing a usePrefetch hook
const prefetchCallback = api.usePrefetch(endpointName, options)

Signature

type UsePrefetch = (
endpointName: string,
options?: UsePrefetchOptions
) => PrefetchCallback

type UsePrefetchOptions =
| {
// If specified, only runs the query if the difference between `new Date()` and the last
// `fulfilledTimeStamp` is greater than the given value (in seconds)
ifOlderThan?: false | number
}
| {
// If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query
// will be run even if it exists in the cache.
force?: boolean
}

type PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => void
  • Parameters

    • endpointName: The name of the endpoint to prefetch data for
    • options: 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

Description

A React hook which can be used to initiate fetching data ahead of time.

Features

  • Manual control over firing a request to retrieve data