Apollo 1: Queries & useQuery
easy⏱ 5 mincourseapollo
What is useQuery?
The useQuery hook is how you fetch data with Apollo Client in React. You pass it a GraphQL query (tagged with gql) and it returns an object with three key fields: loading (boolean while the request is in flight), error (an ApolloError if something went wrong), and data (the result once resolved). Apollo automatically normalizes the response into its in-memory cache using each object's __typename and id, meaning subsequent queries for the same data are served instantly from cache.
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name} — {user.email}</li>
))}
</ul>
);
}
Fetch and display a user list
Define a GET_USERS query with gql that selects id, name, and email from a users field. Use useQuery(GET_USERS) inside a UserList component and destructure { loading, error, data }. Render a loading message, an error message, or a <ul> of users. Export App as the default.
Skip option for conditional queries
Pass skip: true to useQuery to prevent the query from executing. This is useful when you need a value (like a selected ID) before the query makes sense: useQuery(GET_USER, { variables: { id }, skip: !id }). The hook still returns { loading: false, data: undefined } while skipped, so your UI stays consistent.
const { data } = useQuery(GET_USER_DETAIL, {
variables: { id: selectedId },
skip: !selectedId,
});
Automatic cache normalization
Apollo's InMemoryCache splits every object in a query result by its __typename and id (or _id). If two different queries return the same user, Apollo stores only one copy. When a mutation updates that user, every query referencing it re-renders automatically. This is the single most important concept in Apollo — the cache is the source of truth.