What is useQuery and how does it work?
As you learned in the previous chapter, a query is a request you send to an asynchronous source to fetch data.
In the React Query documentation, queries are also defined in the following way:
A query is a declarative dependency on an asynchronous source of data that is tied to a unique key.
(https://tanstack.com/query/v4/docs/guides/queries)
With that concept under your belt, you are now ready to understand how React Query leverages its custom hook, called useQuery
, to enable you to subscribe to a query.
To use the useQuery
custom hook, you have to import it like this:
import { useQuery } from "@tanstack/react-query";
Here is the useQuery
syntax:
const values = useQuery({ queryKey: <insertQueryKey>, queryFn: <insertQueryFunction>, });
As you can see, the useQuery
hook only needs two parameters for it to work:
- A query key: A unique key used to identify...