API Slices: React Hooks

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:

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

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:

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.

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

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

summary

skipToken

summary

See also Skipping queries with TypeScript using skipToken

useMutation

Signature

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

:::

  • 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 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

Description

summary

useQueryState

Signature

  • 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

summary

useQuerySubscription

Signature

  • 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

summary

useLazyQuery

Signature

  • 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

summary

useLazyQuerySubscription

Signature

  • 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

summary

usePrefetch

Signature

  • 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

Last updated

Was this helpful?