useQuery Hook
You'll learn how to fetch data declaratively in React components using Apollo Client's useQuery hook.
What Is useQuery?
The useQuery hook is your main tool for fetching data with Apollo Client. Instead of manually calling an API and managing loading states, errors, and data yourself, useQuery does all this work automatically. Think of it like ordering food delivery — you place your order (the query), then the hook tells you when it's "on the way" (loading), if something went wrong (error), or when your meal has arrived (data).
How It Works
When you call useQuery with a GraphQL query, it immediately starts fetching and returns an object with three key properties:
loading:truewhile the request is in flight,falsewhen doneerror: Contains error information if something went wrongdata: Your actual query results once successful
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
}
}
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading users...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Automatic Refetching
By default, useQuery automatically refetches when your component mounts or when variables change. It also integrates with Apollo's cache, so repeated queries can be served instantly without new network requests.
Key Takeaway: The useQuery hook provides a declarative way to fetch GraphQL data with built-in loading, error, and data state management, handling the complexity of data fetching automatically.