SIGN IN SIGN UP
TanStack / query UNCLAIMED

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

48963 0 0 TypeScript
2020-07-07 23:34:10 -06:00
---
id: overview
title: Overview
---
2023-02-04 13:51:23 -07:00
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes **fetching, caching, synchronizing and updating server state** in your web applications a breeze.
2020-07-07 23:34:10 -06:00
## Motivation
Most core web frameworks **do not** come with an opinionated way of fetching or updating data in a holistic way. Because of this developers end up building either meta-frameworks which encapsulate strict opinions about data-fetching, or they invent their own ways of fetching data. This usually means cobbling together component-based state and side-effects, or using more general purpose state management libraries to store and provide asynchronous data throughout their apps.
2020-07-07 23:34:10 -06:00
While most traditional state management libraries are great for working with client state, they are **not so great at working with async or server state**. This is because **server state is totally different**. For starters, server state:
- Is persisted remotely in a location you do not control or own
- Requires asynchronous APIs for fetching and updating
- Implies shared ownership and can be changed by other people without your knowledge
- Can potentially become "out of date" in your applications if you're not careful
Once you grasp the nature of server state in your application, **even more challenges will arise** as you go, for example:
- Caching... (possibly the hardest thing to do in programming)
- Deduping multiple requests for the same data into a single request
- Updating "out of date" data in the background
2020-07-07 23:34:10 -06:00
- Knowing when data is "out of date"
- Reflecting updates to data as quickly as possible
- Performance optimizations like pagination and lazy loading data
- Managing memory and garbage collection of server state
- Memoizing query results with structural sharing
2020-07-07 23:34:10 -06:00
If you're not overwhelmed by that list, then that must mean that you've probably solved all of your server state problems already and deserve an award. However, if you are like a vast majority of people, you either have yet to tackle all or most of these challenges and we're only scratching the surface!
React Query is hands down one of the _best_ libraries for managing server state. It works amazingly well **out-of-the-box, with zero-config, and can be customized** to your liking as your application grows.
React Query allows you to defeat and overcome the tricky challenges and hurdles of _server state_ and control your app data before it starts to control you.
On a more technical note, React Query will likely:
- Help you remove **many** lines of complicated and misunderstood code from your application and replace with just a handful of lines of React Query logic.
- Make your application more maintainable and easier to build new features without worrying about wiring up new server state data sources
- Have a direct impact on your end-users by making your application feel faster and more responsive than ever before.
- Potentially help you save on bandwidth and increase memory performance
[//]: # 'Example'
2020-07-07 23:34:10 -06:00
## Enough talk, show me some code already!
In the example below, you can see React Query in its most basic and simple form being used to fetch the GitHub stats for the React Query GitHub project itself:
2020-07-07 23:34:10 -06:00
[Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/main/examples/react/simple)
2020-07-07 23:34:10 -06:00
```tsx
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
const queryClient = new QueryClient()
2020-07-07 23:34:10 -06:00
export default function App() {
return (
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
<QueryClientProvider client={queryClient}>
<Example />
v3 (#1360) * feat: initial v3 changes (#1079) * force website deploy * docs: v3 updates * docs: More documentation improvements * docs: update query filters page * docs: update query keys * docs: more updates * docs: updates * feat: support multiple subscribers in observers * docs: useMutation updates * fix: mutate argument types and state update order * fix: remove cache argument in cache callback * fix: move optimistic fetching state into query observer * fix: make sure default options can be overridden * fix: type improvements * feat: memoize select function result * fix: only suspend when mounting * docs: refactor to top level pages and multiple api reference pages per export * test: add remove query test * feat: add filters client isFetching and useIsFetching hook * docs: temp move docs back to docs directory * docs: solve conflicts * docs: fix queryClient reference * docs: reorg directory structure * docs: fix queryClient reference * docs: fix links * docs: better phrasing * docs: force docs build * docs: update examples * fix: use updatedAt to check for existing data * feat: add structural sharing to select result * refactor: update hashing terminology * test: add ability to wrap react query updates with React act * refactor: replace console with logger implementation * docs: add migration page to navigation * docs: update installation docs * refactor: reduce file size * docs: update examples * fix: always compare query keys as arrays * refactor: mark observers as private * test: update timings in hydration cache time test * docs: Update queries.md (#1134) * feat: split mutate into mutate and mutateAsync (#1130) * feat: split mutate into mutate and mutateAsync * docs: Update docs/src/pages/guides/mutations.md Co-authored-by: Tanner Linsley <tannerlinsley@gmail.com> * feat: add bi-directional infinite query support (#1135) * refactor: reduce file size * feat: revert to previous state on cancellation * fix: wait for all queries to cancel * docs: update cancellation docs * build: force * build: add beta build * build: add beta build * docs: update comparison * fix: support infinite cache time when hydrating * refactor: explicitly mark package side effects * docs: update comparison * docs: update comparison * fix: remove excess exports * feat: add support for default options when hydrating * docs: fix links * feat: add options to setQueryData * fix: align notify terminology * feat: Major semver bump BREAKING CHANGE: Increment Major Version * fix: always try to fetch if enabled * feat: bump version * fix: refetch should create new query when removed * chore: do not publish beta until we figure this out * make beta prerelease * dry run releases * fix: test dry run semantic release * release beta releases for realzies * test: add eslint rule * docs(useQuery): change manual to enabled (#1167) * feat: move mutations into the core (#1162) * feat: tree shake infinite query and support manual updates * docs: update comparison * refactor: remove observer factory * refactor: add subscribable * refactor: move hasListeners * refactor: optimize bundle * fix: add status bools to use mutation result * feat: api update * fix: add defaults to UseMutationOptions type * docs: add pages * fix: cleanup * refactor: use queryCache property directly * docs: Add placeholder data guide * docs: fix typo * fix: keep previous query status when fetching * fix: stop retry when observers unmount * feat: add additional notify flags * fix: only keep notify on stale option * refactor: only batch react callbacks * test: update timings * refactor: also batch in suspense * feat: add hydration support for mutations * fix: remove query immediately if cacheTime is 0 * fix: prevent infinite fetch loop * refactor: move refetch logic into observer * fix: match query key correctly when setting defaults * test: add query defaults test * fix: re-add useMutation callback composition * feat: use set defaults also for observers * test: add enabled assertion * feat: add ability to manually control the online and focus state * docs: update onlineManager documentation * feat: add discriminated unions for query results (#1247) * fix: only set state in listeners when provided * docs: add testing page * feat: add query function context (#1261) * feat: add errorUpdatedAt property * fix: only trigger suspense when loading for the first time * fix: make sure suspense is always triggered when loading a query * fix: add ability to type the query key in the query function context * refactor: make isDataEqual type more specific * docs: update react native focus code * fix: make sure to remove the correct query from cache * test: remove only * feat: add granular component re-render control * fix: make sure component re-render when they should * feat: throw error when QueryClientProvider has not been used to set a query client (#1309) Also updated docs * test: add invalidateQueries test * fix: prevent state update after mutation unmounted * fix: add defaults to setQueryData * fix: cancellations for useInfiniteQuery (#1359) * chore: update TypeScript version (#1314) * Merge branch 'master' into beta * fix(hydration): set fetchMeta to null by default to make it serializable (#1371) * fix(hasPageParam): look for (undefined | null | false) values * chore: fix linting * fix: cross-bundle/version query client context * docs: Update Examples * docs: update example deps * docs: keepPreviousData not set in paginated queries docs (#1376) * docs: typo infinite instead of ininite (#1379) * feat: devtools are now native to the core repo/npm-package * feat(persist-localstorage-experimental): temporarily persist cache to disk * tests: fix linting * chore: attempt codesandbox import fix * chore: revert codesandbox fix * fix(persist-localstorage): add ssr-safety * docs: fix typos in migration and queries guide (#1387) Fix typos in guides/migrating-to-react-query-3 and guides/queries. Fixes #1378 * docs(typos): fix typos in mutations guide (#1392) * docs: update migration guide * docs: update comparison * chore: remove vercel.json * docs: update comparison * Update logo.sketch * feat: reset query utils (#1375) * feat: reset query utils * Update queryClient.ts * Reset query docs and tests (#1393) * docs: Add resetQueries * test: Add resetQueries tests * remove unnecessary queryCache.reset methods Co-authored-by: Aaron Jensen <aaronjensen@gmail.com> * types: fix mutation context type * fix: isFetched and isFetchedAfterMount should include failed fetches * docs: Persist localstorage plugin * feat: resetQueries refetches active queries (#1397) Co-authored-by: Niek Bosch <just.niek@gmail.com> Co-authored-by: Abhijeet Singh <contact.abhijeetsingh@gmail.com> Co-authored-by: JP Angelle <jp@angelle.me> Co-authored-by: Jake Ginnivan <jake@ginnivan.net> Co-authored-by: Tom Klaver <tomklav@gmail.com> Co-authored-by: Dmitry Ivanov <liseniss@gmail.com> Co-authored-by: Corentin Leruth <tinencor@gmail.com> Co-authored-by: ConneXNL <contact@ivia-solutions.com> Co-authored-by: Rubén Moya <rmoyarodriguez@gmail.com> Co-authored-by: Pascal Wegner <p.wegner1992@gmail.com> Co-authored-by: Amen SOUISSI <48829921+amen-souissi@users.noreply.github.com> Co-authored-by: Aaron Jensen <aaronjensen@gmail.com>
2020-12-13 19:34:19 -07:00
</QueryClientProvider>
)
}
function Example() {
const { isLoading, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: () =>
2024-01-26 19:48:34 +11:00
fetch('https://api.github.com/repos/TanStack/query').then((res) =>
res.json(),
),
})
2020-07-07 23:34:10 -06:00
if (isLoading) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{' '}
<strong> {data.stargazers_count}</strong>{' '}
<strong>🍴 {data.forks_count}</strong>
</div>
)
}
```
[//]: # 'Example'
[//]: # 'Materials'
2020-09-23 13:36:25 -06:00
## You talked me into it, so what now?
- Consider taking the official [React Query Course](https://ui.dev/react-query?from=tanstack) (or buying it for your whole team!)
- Learn React Query at your own pace with our amazingly thorough [Walkthrough Guide](../installation) and [API Reference](../reference/useQuery)
[//]: # 'Materials'