Skip to content

Commit 0075ca9

Browse files
authored
Merge pull request #1138 from reduxjs/docs/final-rtkq-cleanup
2 parents f9f85c7 + 9e76b6b commit 0075ca9

24 files changed

+398
-166
lines changed

docs/introduction/getting-started.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,9 @@ Redux Toolkit includes these APIs:
7171

7272
## RTK Query
7373

74-
**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
74+
[**RTK Query**](../rtk-query/overview.md) is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
7575

76-
RTK Query is built on top of the Redux Toolkit core for it's implementation, using [Redux](https://redux.js.org/) internally for it's architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
76+
RTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
7777

7878
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
7979

@@ -94,6 +94,8 @@ RTK Query includes these APIs:
9494
- [`<ApiProvider />`](../rtk-query/api/ApiProvider.mdx): Can be used as a `Provider` if you **do not already have a Redux store**.
9595
- [`setupListeners()`](../rtk-query/api/setupListeners.mdx): A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
9696

97+
See the [**RTK Query Overview**](../rtk-query/overview.md) page for more details on what RTK Query is, what problems it solves, and how to use it.
98+
9799
## Learn Redux
98100

99101
We have a variety of resources available to help you learn Redux.

docs/rtk-query/api/ApiProvider.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Using this together with an existing Redux store will cause them to conflict wit
2020
### Example
2121

2222
<iframe
23-
src="https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/feature/v1.6-integration/examples/query/react/with-apiprovider?fontsize=12&hidenavigation=1&module=%2Fsrc%2FApp.tsx&theme=dark"
23+
src="https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/feature/v1.6-integration/examples/query/react/with-apiprovider?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2FApp.tsx&theme=dark"
2424
style={{
2525
width: '100%',
2626
height: '800px',

docs/rtk-query/comparison.md

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ In general, the main reasons to use RTK Query are:
2727
RTK Query has some unique API design aspects and capabilities that are worth considering.
2828

2929
- With React Query and SWR, you usually define your hooks yourself, and you can do that all over the place and on the fly. With RTK Query, you do so in one central place by defining an "API slice" with multiple endpoints ahead of time. This allows for a more tightly integrated model of mutations automatically invalidating/refetching queries on trigger.
30-
- With the endpoint [matcher functionality](./api/created-api/endpoints#matchers): Every request is automatically is visible to your Redux reducers and can easily update the global application state if necessary ([see example](https://github.com/reduxjs/redux-toolkit/issues/958#issuecomment-809570419)).
30+
- Because RTK Query dispatches normal Redux actions as requests are processed, all actions are visible in the Redux DevTools. Additionally, every request is automatically is visible to your Redux reducers and can easily update the global application state if necessary ([see example](https://github.com/reduxjs/redux-toolkit/issues/958#issuecomment-809570419)). You can use the endpoint [matcher functionality](./api/created-api/endpoints#matchers) to do additional processing of cache-related actions in your own reducers.
31+
- Like Redux itself, the main RTK Query functionality is UI-agnostic and can be used with any UI layer
3132
- You can easily invalidate entities or patch existing query data (via `util.updateQueryData`) from middleware.
3233
- RTK Query enables [streaming cache updates](./usage/streaming-updates.mdx), such as updating the initial fetched data as messages are received over a websocket, and has built in support for [optimistic updates](./usage/optimistic-updates.mdx) as well.
33-
- Like Redux itself, the main RTK Query functionality is UI-agnostic and can be used with any UI layer
3434
- RTK Query ships a very tiny and flexible fetch wrapper: [`fetchBaseQuery`](./api/fetchBaseQuery.mdx). It's also very easy to [swap our client with your own](./usage/customizing-queries.mdx), such as using `axios`, `redaxios`, or something custom.
35-
- RTK Query has [a (currently experimental) code-gen tool](https://github.com/rtk-incubator/rtk-query-codegen) that will take an OpenAPI spec and give you a typed API client, as well as provide methods for enhancing the generated client after the fact.
35+
- RTK Query has [a (currently experimental) code-gen tool](https://github.com/rtk-incubator/rtk-query-codegen) that will take an OpenAPI spec or GraphQL schema and give you a typed API client, as well as provide methods for enhancing the generated client after the fact.
3636

3737
## Tradeoffs
3838

@@ -45,6 +45,19 @@ RTK Query deliberately **does _not_ implement a cache that would deduplicate ide
4545
- In many cases, simply refetching data when it's invalidated works well and is easier to understand
4646
- At a minimum, RTKQ can help solve the general use case of "fetch some data", which is a big pain point for a lot of people
4747

48+
### Bundle Size
49+
50+
RTK Query adds a fixed one-time amount to your app's bundle size. Since RTK Query builds on top of Redux Toolkit and React-Redux, the added size varies depending on whether you are already using those in your app. The estimated min+gzip bundle sizes are:
51+
52+
- If you are using RTK already: ~9kb for RTK Query and ~2kb for the hooks.
53+
- If you are not using RTK already:
54+
- Without React: 17 kB for RTK+dependencies+RTK Query
55+
- With React: 19kB + React-Redux, which is a peer dependency
56+
57+
Adding additional endpoint definitions should only increase size based on the actual code inside the `endpoints` definitions, which will typically be just a few bytes.
58+
59+
The functionality included in RTK Query quickly pays for the added bundle size, and the elimination of hand-written data fetching logic should be a net improvement in size for most meaningful applications.
60+
4861
## Comparing Feature Sets
4962

5063
It's worth comparing the feature sets of all these tools to get a sense of their similarities and differences.

docs/rtk-query/overview.md

Lines changed: 109 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,19 @@ hide_title: true
99

1010
# RTK Query Overview
1111

12+
:::tip What You'll Learn
13+
14+
- What RTK Query is and what problems it solves
15+
- What APIs are included in RTK Query
16+
- Basic RTK Query usage
17+
18+
:::
19+
1220
**RTK Query** is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, **eliminating the need to hand-write data fetching & caching logic yourself**.
1321

1422
RTK Query is **an optional addon included in the Redux Toolkit package**, and its functionality is built on top of the other APIs in Redux Toolkit.
1523

16-
### Motivation
24+
## Motivation
1725

1826
Web applications normally need to fetch data from a server in order to display it. They also usually need to make updates to that data, send those updates to the server, and keep the cached data on the client in sync with the data on the server. This is made more complicated by the need to implement other behaviors used in today's applications:
1927

@@ -31,10 +39,14 @@ RTK Query takes inspiration from other tools that have pioneered solutions for d
3139
- The data fetching and caching logic is built on top of Redux Toolkit's `createSlice` and `createAsyncThunk` APIs
3240
- Because Redux Toolkit is UI-agnostic, RTK Query's functionality can be used with any UI layer
3341
- API endpoints are defined ahead of time, including how to generate query parameters from arguments and transform responses for caching
34-
- RTK Query can also generate React hooks that encapsulate the entire data fetching process, provide `data` and `isFetching` fields to components, and manage the lifetime of cached data as components mount and unmount
42+
- RTK Query can also generate React hooks that encapsulate the entire data fetching process, provide `data` and `isLoading` fields to components, and manage the lifetime of cached data as components mount and unmount
43+
- RTK Query provides "cache entry lifecycle" options that enable use cases like streaming cache updates via websocket messages after fetching the initial data
44+
- We have early working examples of code generation of API slices from OpenAPI and GraphQL schemas
3545
- Finally, RTK Query is completely written in TypeScript, and is designed to provide an excellent TS usage experience
3646

37-
### What's included
47+
## What's included
48+
49+
### APIs
3850

3951
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
4052

@@ -53,10 +65,101 @@ RTK Query includes these APIs:
5365
- [`<ApiProvider />`](./api/ApiProvider.mdx): Can be used as a `Provider` if you **do not already have a Redux store**.
5466
- [`setupListeners()`](./api/setupListeners.mdx): A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
5567

68+
### Bundle Size
69+
70+
RTK Query adds a fixed one-time amount to your app's bundle size. Since RTK Query builds on top of Redux Toolkit and React-Redux, the added size varies depending on whether you are already using those in your app. The estimated min+gzip bundle sizes are:
71+
72+
- If you are using RTK already: ~9kb for RTK Query and ~2kb for the hooks.
73+
- If you are not using RTK already:
74+
- Without React: 17 kB for RTK+dependencies+RTK Query
75+
- With React: 19kB + React-Redux, which is a peer dependency
76+
77+
Adding additional endpoint definitions should only increase size based on the actual code inside the `endpoints` definitions, which will typically be just a few bytes.
78+
79+
The functionality included in RTK Query quickly pays for the added bundle size, and the elimination of hand-written data fetching logic should be a net improvement in size for most meaningful applications.
80+
81+
## Basic Usage
82+
83+
### Create an API Slice
84+
85+
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
86+
87+
```ts
88+
import { createApi } from '@reduxjs/toolkit/query'
89+
90+
/* React-specific entry point that automatically generates
91+
hooks corresponding to the defined endpoints */
92+
import { createApi } from '@reduxjs/toolkit/query/react'
93+
```
94+
95+
For typical usage with React, start by importing `createApi` and defining an "API slice" that lists the server's base URL and which endpoints we want to interact with:
96+
97+
```ts
98+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
99+
import { Pokemon } from './types'
100+
101+
// Define a service using a base URL and expected endpoints
102+
export const pokemonApi = createApi({
103+
reducerPath: 'pokemonApi',
104+
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
105+
endpoints: (builder) => ({
106+
getPokemonByName: builder.query<Pokemon, string>({
107+
query: (name) => `pokemon/${name}`,
108+
}),
109+
}),
110+
})
111+
112+
// Export hooks for usage in functional components, which are
113+
// auto-generated based on the defined endpoints
114+
export const { useGetPokemonByNameQuery } = pokemonApi
115+
```
116+
117+
### Configure the Store
118+
119+
The "API slice" also contains an auto-generated Redux slice reducer and a custom middleware that manages suscription lifetimes. Both of those need to be added to the Redux store:
120+
121+
```ts
122+
import { configureStore } from '@reduxjs/toolkit'
123+
// Or from '@reduxjs/toolkit/query/react'
124+
import { setupListeners } from '@reduxjs/toolkit/query'
125+
import { pokemonApi } from './services/pokemon'
126+
127+
export const store = configureStore({
128+
reducer: {
129+
// Add the generated reducer as a specific top-level slice
130+
[pokemonApi.reducerPath]: pokemonApi.reducer,
131+
},
132+
// Adding the api middleware enables caching, invalidation, polling,
133+
// and other useful features of `rtk-query`.
134+
middleware: (getDefaultMiddleware) =>
135+
getDefaultMiddleware().concat(pokemonApi.middleware),
136+
})
137+
138+
// optional, but required for refetchOnFocus/refetchOnReconnect behaviors
139+
// see `setupListeners` docs - takes an optional callback as the 2nd arg for customization
140+
setupListeners(store.dispatch)
141+
```
142+
143+
### Use Hooks in Components
144+
145+
Finally, import the auto-generated React hooks from the API slice into your component file, and call the hooks in your component with any needed parameters. RTK Query will automatically fetch data on mount, re-fetch when parameters change, provide `{data, isFetching}` values in the result, and re-render the component as those values change:
146+
147+
```ts
148+
import * as React from 'react'
149+
import { useGetPokemonByNameQuery } from './services/pokemon'
150+
151+
export default function App() {
152+
// Using a query hook automatically fetches data and returns query values
153+
const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur')
154+
155+
// render UI based on data and loading state
156+
}
157+
```
158+
56159
## Further Information
57160

58-
See the [RTK Query Quick Start tutorial](../tutorials/rtk-query.mdx/) for examples of how to add RTK Query to a project that uses Redux Toolkit, set up an "API slice" with endpoint definitions, and how to use the auto-generated React hooks in your components.
161+
See the [**RTK Query Quick Start tutorial**](../tutorials/rtk-query.mdx/) for examples of how to add RTK Query to a project that uses Redux Toolkit, set up an "API slice" with endpoint definitions, and how to use the auto-generated React hooks in your components.
59162

60-
The [RTK Query usage guide section](./usage/queries.mdx) has information on topics like [querying data](./usage/queries.mdx), [using mutations to send updates to the server](./usage/mutations.mdx), [streaming cache updates](./usage/streaming-updates.mdx), and much more.
163+
The [**RTK Query usage guide section**](./usage/queries.mdx) has information on topics like [querying data](./usage/queries.mdx), [using mutations to send updates to the server](./usage/mutations.mdx), [streaming cache updates](./usage/streaming-updates.mdx), and much more.
61164

62-
The [Examples page](./usage/examples.mdx) has runnable CodeSandboxes that demonstrate topics like [making queries with GraphQL](./usage/examples.mdx#react-with-graphql), [authentication](./usage/examples.mdx#authentication), and even [using RTK Query with other UI libraries like Svelte](./usage/examples.mdx#svelte).
165+
The [**Examples page**](./usage/examples.mdx) has runnable CodeSandboxes that demonstrate topics like [making queries with GraphQL](./usage/examples.mdx#react-with-graphql), [authentication](./usage/examples.mdx#authentication), and even [using RTK Query with other UI libraries like Svelte](./usage/examples.mdx#svelte).

0 commit comments

Comments
 (0)