--- id: queries title: Queries --- ## Query Basics A query is a declarative dependency on an asynchronous source of data that is tied to a **unique key**. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using [Mutations](../mutations.md) instead. To subscribe to a query in your components or custom hooks, call the `useQuery` hook with at least: - A **unique key for the query** - A function that returns a promise that: - Resolves the data, or - Throws an error [//]: # 'Example' ```tsx import { useQuery } from '@tanstack/react-query' function App() { const info = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList }) } ``` [//]: # 'Example' The **unique key** you provide is used internally for refetching, caching, and sharing your queries throughout your application. The query result returned by `useQuery` contains all of the information about the query that you'll need for templating and any other usage of the data: [//]: # 'Example2' ```tsx const result = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList }) ``` [//]: # 'Example2' The `result` object contains a few very important states you'll need to be aware of to be productive. A query can only be in one of the following states at any given moment: - `isPending` or `status === 'pending'` - The query has no data yet - `isError` or `status === 'error'` - The query encountered an error - `isSuccess` or `status === 'success'` - The query was successful and data is available Beyond those primary states, more information is available depending on the state of the query: - `error` - If the query is in an `isError` state, the error is available via the `error` property. - `data` - If the query is in an `isSuccess` state, the data is available via the `data` property. - `isFetching` - In any state, if the query is fetching at any time (including background refetching) `isFetching` will be `true`. For **most** queries, it's usually sufficient to check for the `isPending` state, then the `isError` state, then finally, assume that the data is available and render the successful state: [//]: # 'Example3' ```tsx function Todos() { const { isPending, isError, data, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList, }) if (isPending) { return Loading... } if (isError) { return Error: {error.message} } // We can assume by this point that `isSuccess === true` return (