Make requests with React Query
You can make requests with the useQuery hook, which takes an identifier for your query (in this case, since we are fetching user data, we will call it ‘user’), plus a function that is used to fetch that data.
import { useQuery } from "react-query";
export default function App() {
const { isLoading, isError, data } = useQuery("user", () =>
fetch("https://randomuser.me/api").then((res) => res.json())
);
if (isLoading) return "Loading...";
if (isError) return "Error!";
const user = data.results[0];
return user.email;
}Get Saeed Badghaish’s stories in your inbox
Join Medium for free to get updates from this writer.
As you can see, React Query takes care of managing these various states that can take place when we fetch our data. We no longer need to manage these states ourselves, we can just destructure them from what is returned from useQuery.
Where does the state management part of useQuery come into play?
Now that we have fetched the user data and have it stored in our internal cache, all we need to do to be able to use it across any other component is to call
useQuery()with the 'user' key that we associated with it:
import { useQuery } from "react-query";
export default function OtherComponent() {
const { data } = useQuery('user');
console.log(data);
}





