0Pricing
React Academy · Lesson

useQuery and useMutation Hooks

Fetch data with useQuery, execute mutations with useMutation, and handle loading, error, and data states.

useQuery and useMutation Hooks is a free React Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Defining a Query with gql

The gql template tag from @apollo/client parses a GraphQL query string into a DocumentNode at module load time. Define queries outside components: const GET_USERS = gql`query GetUsers { users { id name email } }`.

Note: in production code, use single-quoted strings wrapped by gql as a tagged template. The gql tag accepts a template literal syntax in JavaScript source.

useQuery Return Values

useQuery(GET_USERS) returns { loading, error, data, refetch, fetchMore, networkStatus }. loading is true during the initial fetch. error contains any GraphQL or network errors. data contains the query result matching the query shape.

Check loading and error first before accessing data to avoid rendering null values.

Loading and Error UI Patterns

Render a skeleton component while loading is true. Render an error message if error is defined (access error.message for the error text). Only render the actual content when data is defined and loading is false.

This three-state pattern (loading / error / data) is the standard Apollo Client component structure.

Accessing Query Data

The data object mirrors the GraphQL query structure. For query { users { id name } }, access data.users which is an array of {id, name} objects. TypeScript types match if you use graphql-codegen to generate typed hooks.

Without codegen, data is typed as any. With codegen, useQuery returns fully typed data automatically.

Variables in useQuery

Pass variables as the second argument: useQuery(GET_USER, { variables: { id: userId } }). The query is automatically re-run when userId changes, just like a useEffect dependency array.

Apollo Client caches each unique combination of query + variables separately, so GET_USER with id: "1" and GET_USER with id: "2" have independent cache entries.

Skipping a Query

Pass skip: true in the options to prevent the query from running: useQuery(GET_USER, { skip: !userId }). Apollo does not fire the request when skip is true, and loading is false, data is undefined.

This is the Apollo equivalent of SWR's null key and React Query's enabled: false option.

Refetching Manually

The refetch function returned by useQuery triggers a network request regardless of the fetch policy. Call refetch() after a user action that may have changed the server data: refetch() after submitting a form, for instance.

Pass new variables to refetch: refetch({ id: newId }) to refetch with different parameters.

Network Status Tracking

Pass notifyOnNetworkStatusChange: true in options to receive updates when the network status changes (fetching, refetching, polling, etc.). The networkStatus field contains a numeric code from the NetworkStatus enum.

This enables showing a subtle "refreshing" indicator when a background refetch is in progress without hiding the current data.

useMutation Signature

useMutation(CREATE_USER) returns [mutateFunction, { loading, error, data, reset }]. The mutate function is called when the user submits a form. It returns a Promise with { data, errors }.

Call mutate({ variables: { name: 'Alice', email: 'alice@example.com' } }) to pass input to the mutation.

onCompleted and onError Callbacks

Pass onCompleted: (data) => navigate('/dashboard') and onError: (error) => showToast(error.message) to useMutation options. These callbacks fire after the mutation resolves or rejects.

onCompleted receives the mutation result data, useful for triggering navigation, displaying success messages, or resetting forms.

Optimistic Response in useMutation

The optimisticResponse option in the mutate call immediately writes a synthetic result to the cache before the server responds. Apollo renders the optimistic data instantly, then replaces it with the real server response when it arrives.

If the mutation fails, Apollo automatically rolls back to the pre-optimistic cache state, keeping the UI consistent.

useQuery skip Option

What happens to a useQuery when skip: true is passed?

Lesson Recap

Define queries with the gql tag, call useQuery(QUERY, { variables, skip }) and handle loading/error/data states. useMutation returns a trigger function and status object; call it with variables and handle results via onCompleted and onError. Optimistic responses update the cache immediately with automatic rollback on failure.

The skip option and variable-driven re-fetching handle conditional and parameterized data loading.

Frequently asked questions

Is the “useQuery and useMutation Hooks” lesson free?

Yes — the full text of “useQuery and useMutation Hooks” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “useQuery and useMutation Hooks”?

Fetch data with useQuery, execute mutations with useMutation, and handle loading, error, and data states. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “useQuery and useMutation Hooks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. GraphQL Fundamentals for React Developers
  2. Setting Up Apollo Client in React
  3. useQuery and useMutation Hooks
  4. Apollo Cache: Normalization and Updates
← Back to React Academy