Query Variables and Dynamic Fetching
You'll learn: How to pass dynamic variables to GraphQL queries, conditionally skip queries, and refetch data when props or state change.
The Core Idea
So far, your Apollo queries have been static — same query, same data, every time. But real apps need dynamic queries that respond to user input, URL params, or component state. Apollo's useQuery hook accepts a variables option that turns your query into a template, and built-in options like skip and reactive variables trigger automatic refetching when dependencies change.
Think of it like a search form: typing a new search term should fetch new results without manually calling a refetch function.
Passing Variables
Define GraphQL variables in your query, then pass them via the variables option:
const GET_USER = gql`
query GetUser($userId: ID!) {
user(id: $userId) {
name
email
}
}
`;
function UserProfile({ userId }) {
const { data, loading } = useQuery(GET_USER, {
variables: { userId }
});
// Apollo automatically refetches when userId changes
}
When userId changes, Apollo detects the variable change and refetches automatically.
Skip Conditions
Prevent queries from running with skip:
const { data } = useQuery(GET_USER, {
variables: { userId },
skip: !userId // Don't query until we have an ID
});
Manual Refetching
The refetch function accepts new variables:
const { refetch } = useQuery(GET_USER, { variables: { userId } });
// Later:
refetch({ userId: newId });
Apollo's reactivity means you rarely need manual refetching — changing props/state with variables triggers it automatically.
Key Takeaway: Apollo's useQuery accepts variables that make queries dynamic, automatically refetches when variables change, and supports skip to conditionally prevent queries — no manual orchestration needed.