Like the Redux core and Redux Toolkit, RTK Query's primary functionality is UI-agnostic and can be used with any UI layer. RTK Query also includes a version of
createApi designed specifically for use with React, which automatically generates React hooks.
While React hooks are the primary way that the majority of users are expected to be using RTK Query, the library itself uses plain JS logic and can be used both with React Class components, and independent of React itself.
This page documents how to interact with RTK Query when used without React Hooks, in order to make proper use of RTK Query
Cache subscriptions are used to tell RTK Query that it needs to fetch data for an endpoint. A subscription for an endpoint can be added by dispatching the result of the
initiate thunk action creator attached to a query endpoint.
Removing a cache subscription is necessary for RTK Query to identify that cached data is no longer required. This allows RTK Query to clean up and remove old cache data.
The result of dispatching the
initiate thunk action creator of a query endpoint is an object with an
unsubscribe property. This property is a function that when called, will remove the corresponding cache subscription.
Accessing cache data and request status information can be performed using the
select function property of a query endpoint to create a selector and call that with the Redux state. This provides a snapshot of the cache data and request status information at the time it is called.
endpoint.select() function creates a new selector instance - it isn't the actual selector function itself!
Note that unlike the auto-generated query hooks, derived booleans such as
isSuccess are not available here. The raw
status enum is provided instead.
With React hooks, this behavior is instead handled within
Examples of usage without React hooks can be found under the following:
PostDetailcomponent in the
React Class Componentsexample
- The below
Cache Lifetime Subscription Class Componentexample:
- NgRx maintainer Brandon Roberts has written a post called Cousins playing nicely: Experimenting with NgRx Store and RTK Query, which demonstrates some approaches for integrating RTK Query into NgRx
saulmoro/ngrx-rtk-queryimplements an NgRx equivalent of the subscription lifecycle managed in RTKQ's own React hooks