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 '@rtk-incubator/rtk-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 "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 MutationHook = () => [
(
arg: any
) => {
unwrap: () => Promise<ResultTypeFrom<D>>;
},
MutationSubState<D> & RequestStatusFlags
];
  • Returns: a tuple containing:
    • trigger: a function that triggers an update to the data based on the provided argument
    • 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